Performance: Actions for modifying state
This affects how quickly the UI updates after state changes and how much work the browser does to re-render components.
const store = useStore(); function updateStateGood() { store.dispatch('updateMultiple', { count: store.state.count + 1, name: 'New Name', active: true }); } // In store actions: const actions = { updateMultiple({ commit }, payload) { commit('setCount', payload.count); commit('setName', payload.name); commit('setActive', payload.active); } };
const store = useStore(); function updateStateBad() { store.state.count++; store.state.name = 'New Name'; store.state.active = true; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct multiple state mutations | Multiple reactive triggers | Multiple reflows | High paint cost due to repeated updates | [X] Bad |
| Batch state changes via actions | Single reactive trigger | Single reflow | Lower paint cost with one update | [OK] Good |
action in state management?fetchData in a Vue component?this.$store.dispatch('actionName') inside a Vue component.commit is used for mutations, not actions. Dispatch is the correct method for actions.count after dispatching incrementAsync?
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
mutations: {
increment(state) {
state.count++
}
},
state: {
count: 0
}setTimeout to delay committing the mutation by 1 second.count is 0. After 1 second, the increment mutation runs, increasing count to 1.actions: {
updateName({ commit }, newName) {
commit('setName', newName)
}
},
mutations: {
setName(state, name) {
state.name = name
}
},
state: {
name: ''
}
What is wrong if dispatching updateName does not update the state?user is a Promise, causing errors.Pass the test and this pattern moves unknown