我是Vue.js
和Axios
的新手。我不太了解如何在组件中使用data
选项。
为什么不这样做?我的测试工作?
我在控制台中收到以下错误:
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. [Vue warn]: Property or method "symbols" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in root instance)
我的简单测试:
我的数据(为简洁起见):
[{"id":1, "name": "Airfield"}, {"id":2, "name": "Ship Yard"}]
我的组件:
Vue.component('symbols-table', {
template: '<h1>Hello World</h1>',
data: {
symbols: []
},
created: function(){
axios.get('symbols.json').then(response => this.symbols = response.data);
}
});
Vue实例:
var app = new Vue({ el: '#app' });
我的HTML :
<symbols-table>
<ul><li v-for="symbol in symbols">{{symbol.name}}</li></ul>
</symbols-table>
答案 0 :(得分:30)
正如错误所说:
&#34;数据&#34;选项应该是一个函数
在组件data must be a function中,您需要将数据块修改为一个函数,该函数将以被动方式返回要在DOM中使用的数据结构:
Vue.component('symbols-table', {
template: '<h1>Hello World</h1>',
data: function() {
return {
symbols: []
}
},
created: function(){
axios.get('symbols.json').then(response => this.symbols = response.data);
}
});
答案 1 :(得分:5)
data
应该是一个返回对象的函数,如the Vue.js common gotchas中所述。
答案 2 :(得分:0)
您可以这样简单地输入:
data() {
return {
...... tra-ta-ta.......
}
},