在 vue 数据中移动数组中的元素不会触发计算元素的重新计算
Moving elements in array in vue data isn't triggering recompute of compueted element
在我的 vue 应用程序中我有
data: {
emailData: JSON.parse('#{{@mail.data}}')
},
computed: {
emailJson: function () {
return JSON.stringify(this.emailData);
}
},
methods: {
addBlock: function (type) {
this.emailData.elements.push({type: type, data: ''})
},
removeBlock: function (index) {
this.emailData.elements.splice(index, 1)
},
moveBlock: function (direction, index) {
if (direction === 'up' && index > 0) {
let temp = this.emailData.elements[index - 1]
this.emailData.elements[index - 1] = this.emailData.elements[index]
this.emailData.elements[index] = temp
} else if (direction === 'down' && index < this.emailData.elements.length) {
let temp = this.emailData.elements[index + 1]
this.emailData.elements[index + 1] = this.emailData.elements[index]
this.emailData.elements[index] = temp
}
}
}
如果我 运行 moveBlock('up',2)
我可以看到 emailData
中的数据已按预期方式更改,但 emailJson
仍显示修改前的数据。如果我稍后调用 addBlock
之前的 moveBlock
和 addBlock
的变化现在显示在 emailJson
.
什么原因会导致 addBlock
和 removeBlock
触发计算值发生变化,但 moveBlock
不会。
看来我的问题是因为 VueJS 在按索引设置时无法检测到数组的更改。如文档中所述 https://vuejs.org/v2/guide/list.html#Caveats
在我的 vue 应用程序中我有
data: {
emailData: JSON.parse('#{{@mail.data}}')
},
computed: {
emailJson: function () {
return JSON.stringify(this.emailData);
}
},
methods: {
addBlock: function (type) {
this.emailData.elements.push({type: type, data: ''})
},
removeBlock: function (index) {
this.emailData.elements.splice(index, 1)
},
moveBlock: function (direction, index) {
if (direction === 'up' && index > 0) {
let temp = this.emailData.elements[index - 1]
this.emailData.elements[index - 1] = this.emailData.elements[index]
this.emailData.elements[index] = temp
} else if (direction === 'down' && index < this.emailData.elements.length) {
let temp = this.emailData.elements[index + 1]
this.emailData.elements[index + 1] = this.emailData.elements[index]
this.emailData.elements[index] = temp
}
}
}
如果我 运行 moveBlock('up',2)
我可以看到 emailData
中的数据已按预期方式更改,但 emailJson
仍显示修改前的数据。如果我稍后调用 addBlock
之前的 moveBlock
和 addBlock
的变化现在显示在 emailJson
.
什么原因会导致 addBlock
和 removeBlock
触发计算值发生变化,但 moveBlock
不会。
看来我的问题是因为 VueJS 在按索引设置时无法检测到数组的更改。如文档中所述 https://vuejs.org/v2/guide/list.html#Caveats