How to set data properties to value returned from Vuex getter How to set data properties to value returned from Vuex getter vue.js vue.js

How to set data properties to value returned from Vuex getter


The data method is only fired once during initialization, before the computed properties are set up. So, referencing currentArea from within the data method won't work as it will be undefined at the time of execution.

If this.$store.getters.currentArea isn't expected to change in the lifespan of this component, it would be simplest to just set the data properties once in the mounted hook:

data() {  return {    name: '',    address: '',    city: '',    state: ''  }},mounted() {  let area = this.$store.getters.currentArea;  this.name = area.name;  this.address = area.address;  this.city = area.city;  this.state = area.state;       } 

Or, if you know that the data properties for this component will always be the same as the currentArea, you could simply return this.$store.getters.currentArea in the data method directly:

data() {  return this.$store.getters.currentArea;}


@thanksd: thank you for your answer. I am working on a scenario where the state is stored in vuex, temporarily sent incomplete to the component and then updated through a fetch. And it should be editable in a form.

My solution was to export part of the state with a getter in vuex:

getters: {  getItemDetail: (state, getters) => (id) => {    let item = state.openedItems.items.find(i => i.id === id);    return item ? item.data : null;  }}