Vue.js 更新了错误的变量
Vue.js wrong variable gets updated
我有一个过滤方法 (itemsWithFilter) 来过滤我的 items 对象并将结果写入 itemsResult
这是第一次工作,但似乎我的函数也自动更新了 items 对象。尽管如此,我还是将结果写在 itemsResult 中。
有谁知道为什么以及如何防止它? itemsWithFilter 方法 returns 结果仅 itemsResult
这里是Fiddlelink:https://jsfiddle.net/afdz3yLt/1/
这是我的 itemsWithFilter 函数
itemsWithFilter: function(filter) {
var items = this.items.data;
var result = {}
console.log("Run itemsWithFilter")
Object.keys(items).forEach(key => {
const item = items[key]
console.log(`filter: ${filter}: check item ${item.id} with category id: ${item.category.id}`)
if (item.category.id == filter) {
result[key] = item
}
})
this.itemsResult.data = result
}
可能是我理解错了问题,但我想你想问的是如何使用 this.items.data
并将结果写入 this.itemsResult.data
而没有 this.items.data
也更新了。这是典型的 JavaScript 事情,其中对对象的引用始终保持不变。您正在寻找的(如果我对问题的假设是正确的)是克隆 this.items.data
对象。最好的方法是
var items = JSON.parse(JSON.stringify(this.items.data))
。这些问题的更多信息:
How to copy JavaScript object to new variable NOT by reference?
What is the most efficient way to deep clone an object in JavaScript?.
我有一个过滤方法 (itemsWithFilter) 来过滤我的 items 对象并将结果写入 itemsResult
这是第一次工作,但似乎我的函数也自动更新了 items 对象。尽管如此,我还是将结果写在 itemsResult 中。
有谁知道为什么以及如何防止它? itemsWithFilter 方法 returns 结果仅 itemsResult
这里是Fiddlelink:https://jsfiddle.net/afdz3yLt/1/
这是我的 itemsWithFilter 函数
itemsWithFilter: function(filter) {
var items = this.items.data;
var result = {}
console.log("Run itemsWithFilter")
Object.keys(items).forEach(key => {
const item = items[key]
console.log(`filter: ${filter}: check item ${item.id} with category id: ${item.category.id}`)
if (item.category.id == filter) {
result[key] = item
}
})
this.itemsResult.data = result
}
可能是我理解错了问题,但我想你想问的是如何使用 this.items.data
并将结果写入 this.itemsResult.data
而没有 this.items.data
也更新了。这是典型的 JavaScript 事情,其中对对象的引用始终保持不变。您正在寻找的(如果我对问题的假设是正确的)是克隆 this.items.data
对象。最好的方法是
var items = JSON.parse(JSON.stringify(this.items.data))
。这些问题的更多信息:
How to copy JavaScript object to new variable NOT by reference?
What is the most efficient way to deep clone an object in JavaScript?.