vuejs2 - Vue.js (v.2) 仅在单击按钮后加载(获取)数据
问题描述
我是 VUE 的初学者,我编写了代码,在加载网页后,从 json 下载数据并使用 id “app” 渲染它。
但是,我需要的数据不是在开始时加载,而是在单击按钮后才加载。
非常感谢您的提示和建议。
const app = new Vue ({
el: '#app',
data: {
urlPrefix: '',
newName: '',
newDescription: '',
newExperts_advice: '',
newProduct_benefit_2: '',
newImage: '',
characters: [{
}
],
},
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,
})
}
},
created: function(){
fetch('./data.json')
.then(res => res.json())
.then(json => this.characters = json)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!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>Fetch data</button>
<div class="info-v1" v-for="item in characters">
<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>
解决方案
首先,您应该在获取数据的方法中创建方法。
methods: {
yourNewMethodToFetchData() {
fetch('./data.json')
.then(res => res.json())
.then(json => this.characters = json)
}
}
第二次将点击事件添加到您的获取数据按钮,如下所示:
<button @click="yourNewMethodToFetchData">Fetch data</button>
created
最后从钩子中删除获取代码:
created: function(){
}
推荐阅读
- vue.js - 异步函数结果
- c - 使用 OpenMP 任务的带中断的并行 for 循环
- powershell - 如何从 Invoke-webrequest 内容结果中钻取数据?
- android - 任务 ':common:kaptDebugKotlin' 执行失败
- azure - Azure devops - 内部版本号与内部版本 ID
- html - xmlns:xlink="http://www.w3.org/1999/xlink" 还有功能吗?
- javascript - 每当我运行 npm install --force 时,我都会遇到此错误
- python - 使用 JDBC 和 Python 连接到 Oracle 数据库
- flutter - 如何在 Flutter 中实现这个小部件
- ember.js - Emberjs:断言失败:尝试注入未知注入:'service:inViewport'