下面的代碼證明不通過mutation,而直接修改state修改確實生效了。這樣子多人協作豈不是很容易出問題。對於這個問題,在創建 store 的時候傳入 strict: true, 開啟嚴格模式,那么任何修改state的操作,只要不經過mutation的函數,vue就會 throw error。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } } }) console.log(store.state.count) //0 store.state.count = 3; console.log(store.state.count) //3
參考文章: https://blog.csdn.net/weixin_40402192/article/details/80052887