如何在组件和Axios中使用数据?

时间:2017-02-22 16:19:01

标签: vue.js vuejs2 axios vue-component

我是Vue.jsAxios的新手。我不太了解如何在组件中使用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>

3 个答案:

答案 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)

Vue组件中的

data应该是一个返回对象的函数,如the Vue.js common gotchas中所述。

答案 2 :(得分:0)

您可以这样简单地输入:

data() {
    return {
        ...... tra-ta-ta.......
    }
},