在我的vue项目中,我有一个组件,它将通过ajax请求加载数据。视图页面将使用此组件3次,请求参数和结果完全相同。我想只调用一次ajax请求。什么是最佳做法?我理解使用vuex存储或会话存储来保存组件中的ajax结果可以做到,但有没有更好的主意?
jsfiddle链接:jsfiddle.net/cqli/5g7anu0f/37
模板:
<div id="app">
<show-title></show-title>
<show-title></show-title>
<show-title></show-title>
</div>
组件定义:
Vue.component('show-title', {
mounted(){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => this.title = json.title);
},
data: function () {
return {
title: "hello world!"
}
},
template:"<h3>{{title}}</h3>"
});
new Vue({
el: "#app",
data: {
},
methods: {
}
})
它们将是相同的,因为您使用相同的数据调用URL:id = 1
。您需要为组件使用props:
Vue.component('show-title', {
props: ['id'], // here you defined props
mounted(){
fetch('https://jsonplaceholder.typicode.com/todos/'+this.id) // here you fetch todo with ID from props.
.then(response => response.json())
.then(json => this.title = json.title);
},
data: function () {
return {
title: "hello world!"
}
},
template:"<h3>{{title}}</h3>"
});
在你的模板中添加:id
:
<show-title :id="1"></show-title>
<show-title :id="2"></show-title>
<show-title :id="3"></show-title>