You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 2.x 实现点击按钮后再加载(Fetch)数据

实现点击按钮后加载Vue数据的解决方案

嘿,没问题!要实现仅点击按钮才加载数据其实很简单,咱们只需要调整一下代码结构,把自动加载的逻辑改成触发式的就行。下面是具体的修改步骤和完整代码:

核心修改思路

  1. 把原来created钩子中自动执行的fetch逻辑,移到一个自定义方法里
  2. 给页面上的按钮绑定点击事件,触发这个自定义方法
  3. (可选)添加加载状态,防止用户重复点击重复请求

修改后的完整代码

JavaScript部分

const app = new Vue ({
 el: '#app',
 data: {
 urlPrefix: '',
 newName: '',
 newDescription: '',
 newExperts_advice: '',
 newProduct_benefit_2: '',
 newImage: '',
 characters: [], // 初始化为空数组,去掉默认占位对象
 isLoading: false // 新增加载状态,优化用户体验
 },
 methods: {
 add() {
 this.characters.push ({
 name: this.newName,
 description: this.newDescription,
 experts_advice: this.newExperts_advice,
 product_benefit_2: this.newProduct_benefit_2,
 image: this.newImage,
 })
 },
 // 新增fetchData方法,专门处理数据加载逻辑
 fetchData() {
 if (this.isLoading) return; // 避免重复点击发送多次请求
 this.isLoading = true;
 fetch('./data.json')
 .then(res => res.json())
 .then(json => {
 this.characters = json;
 this.isLoading = false; // 加载完成后重置状态
 })
 .catch(err => {
 console.error('加载数据失败:', err);
 this.isLoading = false; // 出错也要重置状态
 })
 }
 },
 // 移除原来的created钩子,取消页面初始化时的自动加载
})

HTML部分

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TEST</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
<link rel="icon" href="favicon.ico" type="image/x-icon"/>
</head>
<body>
<div id="app">
<!-- 给按钮绑定点击事件,同时根据加载状态显示不同文案/禁用按钮 -->
<button @click="fetchData" :disabled="isLoading">
 {{ isLoading ? '加载中...' : 'Fetch data' }}
</button>
<div class="info-v1" v-for="item in characters" :key="item.name">
<!-- 给v-for添加key属性,这是Vue的性能优化最佳实践 -->
<section class="head">
<h2>{{ item.name }}</h2>
<p> {{ item.description }}</p>
</section>
<section class="body">
<img v-bind:src="urlPrefix + item.image " />
<h3>{{ item.product_benefit_2 }}</h3>
<p>{{ item.experts_advice }}</p>
</section>
</div>
</div>
</body>
</html>

关键修改说明

  • 移除created钩子:原来的created会在Vue实例创建后自动执行,删掉它就不会在页面加载时自动请求数据了。
  • 新增fetchData方法:把数据请求的逻辑封装在这里,只有当按钮被点击时才会触发执行。
  • 按钮绑定@click事件:用Vue的指令把按钮的点击动作和fetchData方法关联起来,实现点击触发加载。
  • 加载状态优化:新增的isLoading状态可以防止用户重复点击发送多次请求,同时给用户显示加载中的反馈,提升使用体验。
  • v-for添加key:这是Vue官方推荐的做法,有助于Vue更高效地追踪DOM元素,提升渲染性能。

这样修改后,页面加载完成后不会自动获取数据,只有当你点击"Fetch data"按钮时,才会请求data.json并渲染内容~

内容的提问来源于stack exchange,提问作者Števo Kelbel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:32:44