昨天看到一个博客 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同理也是该办法
最初看输入以及页面展现:功败垂成!!!
发表回复