昨天看到一个博客 watch监听无法监听到vuex的state的值 提了两种解决办法:
1.在store.js的state中使用Vue.observable(官方文档有具体说明)
2.在created初始化的时候将data中的属性赋值时指向整个state仓库 而不是赋值单个属性
于是乎 我今天想试试,但是!我的结果都是可以监听到,没有遇到那个问题 因为vuex的state本身就相当于一个响应仓库
1.首先我们新建store.js
1⃣️ 声明count和message两个变量
2⃣️ 在mutation写如下方法 addCount方法让每次加n; watchMessage 则每次将newVal赋值到新message属性之上
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const state = ({
count:11,
message:'hello'
});
const mutations = {
addCount(state,n){
state.count+=n;
},
watchMessage(state,newval){
state.message = newval;
}
};
export default new Vuex.Store({
state,
mutations
});
<template>
<div style="height:5000px;background:#fff;">
<h5>Vuex状态管理store无法watch到改变后的数据</h5>
<el-button @click="addNum">
++
</el-button>{{countNum}}
{{msg}}
<el-button @click="click2">Test</el-button>
{{message}}
</br>
<!-- <el-button @click="$router.push('/vParent')">跳转父组件</el-button> -->
</div>
</template>
<script>
export default {
data(){
return{
// watch监听到了
msg:'888',// plan1.0
}
},
computed:{
countNum(){
return this.$store.state.count
},
message(){
return this.$store.state.message
}
},
watch:{
'$store.state.count':function(newVal){ // plan1.0
if(newVal){
console.log('监听到count')
this.msg = `watch监听到了,值是${this.$store.state.count}`
}else{
this.msg = '监听不到'
}
},
'$store.state.message':function(newVal){
console.log(newVal,'message')
}
},
methods:{
addNum(){
this.$store.commit("addCount",99)
},
click2(){
this.$store.commit('watchMessage','Hello Message')
}
},
created(){
}
}
</script>
1.首先在 computed中 将state中的变量接收 在模板中使用
2.开始在addNum中提交(commit)该方法,传数字99
3.最后watch监听$store.state.count的值 假如有新值的话我们在页面显示!
4.message同理也是该方法
最后看输出以及页面展示:大功告成!!!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。