Vue.js错误的变量得到更新

用户名

我有一个过滤器方法(itemsWithFilter)来过滤我的items对象并将结果写在itemsResult中

这是第一次工作,但似乎我的函数也自动更新了items对象。即使如此,我将结果写在itemsResult中

有谁知道为什么以及如何预防呢?itemsWithFilter方法将结果返回给itemsResult

这是Fiddle链接: 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

}
Imre_G

可能是我理解的问题是错误的,但是我认为您要问的意思是如何使用this.items.data结果并将结果写入其中this.itemsResult.data而不this.items.data进行更新。这是典型的JavaScript事物,其中对对象的引用始终保持不变。您正在寻找的是(如果我对问题的假设是正确的)克隆this.items.data对象。最好的方法是var items = JSON.parse(JSON.stringify(this.items.data))这些问题的更多信息:

如何不通过引用将JavaScript对象复制到新变量?

在JavaScript中深度克隆对象的最有效方法是什么?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章