我正在使用 Vuejs/Nuxtjs 在此应用程序中开发一个应用程序,我有一个组件 IdentifiersNode.vue ,我想在其中监视 Vuex 存储数组 identifiersArray。
我可以观察 identifiersArray 的直接更改,例如 push、直接键值更改,但是当我向 identifiersArray 中的对象添加新对象时,watch 将因某种原因无法工作。
以下是我的IdentifiersNode.vue中的watch函数:
watch: {
'$store.state.modules.identifiersInfoStore.identifiersArray': {
handler (val) {
console.log('WATCH : ' + JSON.stringify(val, null, 4))
},
deep: true
}
},
以下是 Vuex 存储中我的 identifiersArray 发生的更改 endcphpcn 存在于 identifiersInfoStore .js 中:
saveIdentifiersInfo (state, payload) {
// Upon saving the Identifiers info save the information into respective object of identifiersArray
const identifiersNode = state.identifiersArray.find(node => node.identifiersId === state.currentNodeId)
console.log('NODE BEFORE : ' + JSON.stringify(identifiersNode, null, 4))
identifiersNode.instanceData = payload.instanceData
console.log('NODE ARRAY AFTER : ' + JSON.stringify(state.identifiersArray, null, 4))
},
正如我们所看到的,我正在向 identifiersArray 中的现有对象添加一个对象,但是当我这样做时,我希望我的 watch 函数在 IdentifiersNode.vue 中触发,因为我有 deep: true 但由于某种原因,它没有根本没有工作。
有人可以告诉我是否可以使用 Vuex store 和 Vue watch 检测对数组的哪怕是一分钟的更改?如果没有,那么我可以采取什么替代方案?
以下是来自 console.log 的 identifiersNode:
NODE BEFORE : {
"identifiersId": 1,
"name": "identifiersNode1"
}
以下是来自 console.log 的 state.identifiersArray:
NODE ARRAY AFTER : [
{
"identifiersId": 1,
"name": "identifiersNode1",
"instanceData": {
"name": "Batman",
"job":"IT"
}
}
] Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您使用 vuex,我建议使用
mapGetters从商店获取您的商品。这将自动监视值并在每次项目更改时重新渲染。这里是文档:文档
小例子
商店
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const state = { data: ["Hello", "world"] }; const mutations = { addItem(state, item) { state.data.push(item); } }; const getters = { getData: (state) => state.data }; export default new Vuex.Store({ state, mutations, actions, getters })组件
以下是一个 codepen 作为示例: https://codesandbox.io/s/vuex-store-forked-bl9rk0?file=/src/components/HelloWorld.vue
如果您想更改对象属性(或者在您的情况下将新对象添加到作为对象属性的数组中),最好的办法是完全重新推送当前对象。
例如,如果您有一个像
[{id: 1,values:[1,2,3]},{id:2,values:[4,5,6]}]这样的数组,您可以更新值使用 js 拼接方法 :addValue(state, {id, valueToAdd}){ const pos = state.arr.findIndex(x => x.id === id) if (pos !== -1){ const newObj = {...state.arr[pos]} newObj.values.push(value) state.arr.splice(pos, 1, newObj) } }提供答案可能会对将来的其他人有所帮助。
我实际上是将对象附加到 Vuex Store 中数组中的现有对象中。因此,手表无法识别变化。我将其更改为
vue.set这对我有用。以前我使用附加到现有对象:
后来我改为:
以下是我在Vue组件中的手表,我在我的
mounted中使用了这段代码,也可以在手表中使用:// Watch for the changes on the identifiers array this.$watch('$store.state.modules.identifiersInfoStore.identifiersArray', (val) => { console.log(JSON.stringify(val,null,4)) }, { immediate: true, deep: true })