作為一個剛開始用 vuex 的小白,我一開始的用法就是直接修改 state 的狀態,后來看到官網
從組件的方法提交一個變更: methods: { increment() { this.$store.commit('increment') console.log(this.$store.state.count) } }
再次強調,我們通過提交 mutation 的方式,而非直接改變 store.state.count
,是因為我們想要更明確地追蹤到狀態的變化。這個簡單的約定能夠讓你的意圖更加明顯,這樣你在閱讀代碼的時候能更容易地解讀應用內部的狀態改變。此外,這樣也讓我們有機會去實現一些能記錄每次狀態改變,保存狀態快照的調試工具。有了它,我們甚至可以實現如時間穿梭般的調試體驗。
由於 store 中的狀態是響應式的,在組件中調用 store 中的狀態簡單到僅需要在計算屬性中返回即可。觸發變化也僅僅是在組件的 methods 中提交 mutation。
看到這個我就懵了,原來我一直在錯誤的使用,那么問題來了,為什么要通過 mutation 來修改 state 呢?
利用this.$store.state當然可以更改state里面的值,因為這本身就是vuex存值的地方,但是一般不這樣做,因為這樣對於數據來說是不可控制的,一般在開發環境,會產生警告的報錯。如下
原理是vuex源碼中的利用vue的watch功能監聽這個數據
但是,這個監聽有缺陷,就是如果state里面值是數組的話,對數組某個指針進行更改的時候是無法觸發這個監聽的
還是希望按要求在mutation中提交更新,養成良好的習慣
綜上所述,請用computed去接收state,如下
//state.js let state = { count: 1, name: 'dkr', sex: '男', from: 'china' } export default state
<template> <div id="example"> <button @click="decrement">-</button> {{count}} {{dataCount}} <button @click="increment">+</button> </div> </template> <script> export default { data () { return { dataCount: this.$store.state.count //用data接收,后續的修改不實時更新 } }, computed:{ count(){ return this.$store.state.count //用computed接收 } } methods: { increment () { this.$store.commit('increment') }, decrement () { this.$store.commit('decrement') } } } </script>
結果如下,用data接收的值不能及時響應更新,用computed就可以.
通過mutation更新,可以被監聽得到,而且也能讓后人了解你的意圖。