Answer a question

I'm using the created lifecycle hook in vue.js to load data from my store to the data for a vue component. I noticed that this.selectedType = store.state.selectedType successfully loads the data from the store. However, if I use the getter to load from the store (i.e. this.selectedType = store.getters.getType()), I get the following error:

Error in created hook: "TypeError: Cannot read property 'selectedType' of undefined"

I don't understand why it is saying that selectedType is undefined because selectedType has the value "Item" in the store and is correctly loaded on create if I use this.selectedType = store.state.selectedType.

The getter is defined as such:

getters: {
    getSelectedType: state => {
      return state.selectedType
    }
}

And the state is defined as:

state: {
  selectedType: "Item"
}

Could someone please explain why this occurs? I'm hunch is that there is something about the lifecycles that I don't fully understand that is leading to this confusion.

Answers

You are not supposed to call getters. Just like computed properties, you instead write it like you are reading a variable. In the background the function you defined in the Vuex store is called with the state, getters (and possibly rootState and rootGetters) and returns some value.

Beside that, it is usually an anti-pattern to use a lifecycle hook to initialise any variable. Local 'component' variables can be initialised in the data property of the component, while things like the vuex state usually end up in a computed property.

The last thing I want to point out is that, if you have correctly added the store to your Vue application, you can access the store in any component with this.$store. To use getters in your application, you can use the mapGetters helper to map getters to component properties. I would recommend using something like this:

import { mapGetters } from 'vuex';

export default {
  // Omitted some things here

  computed: {
    ...mapGetters({
      selectedType: 'getSelectedType'
    })
  },

  methods: {
    doSomething () {
      console.log(this.selectedType);
    }
  }
}

Which is functionally equivalent to:

computed: {
  selectedType () {
    return this.$store.getters.getSelectedType;
  }
}
Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐