简体   繁体   中英

Data object in component is undefined

I have defined object in data of vue component like this:

export default {
  components: {..}
  data: () => {
    filter: ({
      from: 2017,
      to: 2018
    }
  }),
  computed: mapState({
    fooObjects: (state) => {
      console.log(this.filter) // print undefined
    }
  }),
  ...
}

Can you tell me how to access to my filter object in computed property and why is filter undefined? I've initialize it with 2 years on start as you can see. Thanks.

Don't use arrow functions on computed, they are bound to the parent context, this will not be the Vue instance as you'd expect. Also you should return an object from your data method. This is working below

 export default { components: {..}, data () { return { filter: { from: 2017, to: 2018 } } }, computed: { fooObjects: function () { return console.log(this.filter) } } } 

A couple of things. First your parenthesis do not line up starting at line 4 . Second, in order to access this.filter your data method must return a json object. You have it returning the filter.

The following code should give you access to this.filter .

export default {
  components: {..}
  data: () => {
    return {
      filter: {
        from: 2017,
        to: 2018
      }
    }
  },
  computed: mapState({
    fooObjects: (state) => {
      console.log(this.filter) // print undefined
    }
  }),
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM