app.vue 中:computed: {
obj(){
return this.$store.state.obj;
},
id(){
return this.$store.state.obj.id;
}
},
watch: {
id(){
console.log('idid');
},
obj(){
console.log('objobj');
}
}在 vuex 中設置:const state = {
obj: {
id: 1
}
}
const mutations = {
updateObj(state, obj){
state.obj = obj
},
updateId(state, id){
// Vue.set(state.obj, 'id', id);
state.obj.id = id;
}
}當觸發 updateId 試圖改變 obj 的 id 屬性時,watch 中的 id 會有 Console.log,但 obj 并沒有。意味著,改變 obj.id 時,obj 的變化并沒有被 watch 到。使用 Vue.set 的方式也是一樣。此外,如果直接打印 {{ obj.id }} 是可以輸出正確結果的。但 watch 中就是失效。如果我想做到當 obj 中的任意屬性改變時就觸發某一事件,該如何實現呢?
2 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
更新
誤解你的意思,你是希望能watch對象時,屬性更新也要觸發handler.要用watch的deep屬性
watch: { obj: { deep: true, handler: function () { console.log(123) } } }
原答案
你應該用vuex的getter
// getter
const getters = {
obj: state => state.obj
}
// vue components
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用mapGetters
...mapGetters([
'obj',
// ...
]),
// 使用store屬性
obj () {
return this.$store.getters.obj
}
}
}
添加回答
舉報
0/150
提交
取消