問題:使用Vue簡單狀態管理Store模式,組件中可以獲取到store中的數據,在組件中通過事件改變store中的值,并提交到store后,在store中可以打印出改變后的值,但在組件中通過watch無法監聽到最新值的變化store.jsletstore={state:{message:'Hello!'},setMessageAction(newValue){this.state.message=newValueconsole.log('store.js-newValue:',this.state.message);//當組件改變數據后這里是可以獲取到改變后的最新值的},}exportdefaultstoremain.js中引入store//簡單store模式importstorefrom'./store'Vue.prototype.$store=store組件中使用store{{message}}changeStoreexportdefault{data(){return{message:''}},created(){this.message=this.$store.state.message},watch:{'$store.state.message':function(newVal){//watch無法獲取組件改變后的新值console.log(newVal);console.log(this.$store.state.message);}},methods:{change(){this.$store.setMessageAction('changehelloworld')}},}==============================分割線===================================在asseek和夕水的提示下已經解決問題,下面是我實現的方法,有更好的方法請指出,謝謝:兩種解決方案:使用Vue.observable在組件中可以直接調用state中的某個值引用store.state對象組件中使用需要先把state賦值給組件中data選項解決方案1:修改store.js如下:state用observable定義來實現響應式letstore={state:Vue.observable({message:'Hello!'}),setMessageAction(newValue){this.state.message=newValueconsole.log('store.js-newValue:',this.state.message);},}exportdefaultstore組件調用:{{msg}}changeStoreexportdefault{data(){return{num:0}},computed:{msg(){returnthis.$store.state.message;}},methods:{change(){this.$store.setMessageAction(this.num++)}},}解決方案2:store.jsletstore={state:{message:'Hello!'},setMessageAction(newValue){this.state.message=newValueconsole.log('store.js-newValue:',this.state.message);},}exportdefaultstore組件:{{msg}}changeStoreexportdefault{data(){return{state:'',num:0}},created(){//注意:這里需要賦值state對象,而不能直接賦值對象中的某個值,否則不能觸發響應式this.state=this.$store.state},computed:{msg(){returnthis.$store.state.message;}},methods:{change(){this.$store.setMessageAction(this.num++)}},}
Vue 簡單狀態管理Store模式下無法 watch 到改變后的數據
白衣非少年
2019-08-11 14:01:13