Reputation: 1636
In my store I have...
...
addresses: [ /* array of address objects */ ],
address: { /* holds chosen address */ }
...
In my component, I have...
import {mapState, mapActions} from 'vuex'
export default {
name: 'AddressBook',
watch: {
selectedAddress: function(newval) {
// Update the address
// address and addresses is mapped from the vuex store.
this.address = Object.assign( this.address, this.addresses[newval]);
}
},
data: {
selectedAddress: 0 /* Address selected by index */
}
computed: {
...mapState(['addresses', 'address'])
}
}
Addresses and Address are being mapped from vuex. User chooses an address from a select box of addresses (eg addresses[1])... which is used to update the address.
The thing that has confused me is that updating this.address this way just works... My Vuex store changes. I thought I'd have to dispatch / commit etc..? It just seems too simple.. too easy..
Is it safe to update this.address in this way, at the component level?
Upvotes: 0
Views: 1938
Reputation: 44058
Is it safe to update this.address in this way, at the component level?
No, at the very least you should be committing changes from a mutation (or calling an action that commits a mutation). From the Mutations documentation:
The only way to actually change state in a Vuex store is by committing a mutation.
Also, the way you're modifying address might not be happening how you might think:
this.address = Object.assign( this.address, this.addresses[newval]);
It's nonsensical (maybe impossible? not sure if Vue freezes) to re-assign a computed property like this anyway. What's actually happening is Object.assign
always mutates the first parameter directly. That's why you might often see the empty-object pattern e.g. Object.assign({}, this.address, this.addresses[newval])
At any rate, to avoid subtle accidental mutations like this, you can enable strict mode which will warn you when those unsafe mutations happen.
Upvotes: 1