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; }}
using it in the component by combining data, computed and watch properties (and deep cloning the object with the help of lodash):
data () { return { itemDetail: null };},computed: { itemData () { return this.$store.getters.getItemDetail(this.item.id); }},watch: { itemData (n, o) { this.itemDetail = _.cloneDeep(n); }}
Finally I bind the input to "itemDetail" (using an elemen switch, in my example):
<el-switch v-model="itemDetail.property"></el-switch>
To me (but I am quite new to Vue), it seems a good and working compromise.