stack001 stack001
stack001 stack001

Reputation: 109

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.

Upvotes: 0

Views: 403

Answers (2)

Payton Burdette
Payton Burdette

Reputation: 126

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

Upvotes: 1

Keegan Teetaert
Keegan Teetaert

Reputation: 673

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
    }
  }),
  ...
}

Upvotes: 0

Related Questions