共计 1509 个字符,预计需要花费 4 分钟才能阅读完成。
昨天看到一个博客 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 同理也是该办法 |
最初看输入以及页面展现:功败垂成!!!
正文完