我正在使用 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-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
提供答案可能会对将来的其他人有所帮助。
我实际上是将对象附加到 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 })