33

I'm new to Vue.js and Axios. I don't quite understand how to get the data option to work when used within a component.

Why doesnt' my test work?

I get the following error in the console:

[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)

My simple test:

My data (snipped for brevity):

[{"id":1, "name": "Airfield"}, {"id":2, "name": "Ship Yard"}]

My component:

Vue.component('symbols-table', {
    template: '<h1>Hello World</h1>',
    data: {
        symbols: []
     },
     created: function(){
         axios.get('symbols.json').then(response => this.symbols = response.data);
      }
});

Vue instance:

var app = new Vue({ el: '#app' });

My HTML:

<symbols-table>
    <ul><li v-for="symbol in symbols">{{symbol.name}}</li></ul>
</symbols-table>
Community
  • 1
  • 1
redshift
  • 4,815
  • 13
  • 75
  • 138

3 Answers3

59

As the error is saying:

The "data" option should be a function

In the component, the data must be a function, you need to modify the data block to be a function which will return the data structure to be used in DOM in a reactive way:

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);
    }
});
tony19
  • 125,647
  • 18
  • 229
  • 307
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • 1
    Thanks! Indeed, that was one of the issues...and I should have known that. However, I still get the following error in console: "Property or method "symbols" is not defined on the instance but referenced during render....snip.." . My code looks the same above but with the added data function mentioned. Any ideas? – redshift Feb 22 '17 at 16:40
  • @redshift the problome is you have `symbols` at child level, however you are using it at DOM on parent level. – Saurabh Feb 22 '17 at 16:44
  • 1
    Thanks, that was the issue. – redshift Feb 22 '17 at 16:56
  • Saving tip, I was copying and pasting from the original router-less version and I forgot this detail even though it's mentioned clearly in the docs. Thanks. – cdsaenz May 29 '20 at 19:44
7

data inside a Vue Component should be a function that returns an object, as described in the Vue.js common gotchas.

Ed The ''Pro''
  • 875
  • 10
  • 22
jingman
  • 415
  • 3
  • 10
4

You can type simply like this:

data() {
    return {
        ...... tra-ta-ta.......
    }
},
Elletlar
  • 3,136
  • 7
  • 32
  • 38