【问题标题】:vueJs updating props even though i am method variable即使我是方法变量,vueJs 也会更新道具
【发布时间】:2021-09-12 17:49:51
【问题描述】:

我有以下方法比较两个数组,一个来自道具,另一个来自我自己的组件。我的 props 数组中存在但我的 components 数组中不存在的每个元素都插入到第三个数组中,并添加了名为“destroy:true”的属性,因此我可以将其发送到后端以从数据库中删除。

但是,无论出于何种原因,我的道具都在更新,而不是我在方法中使用的变量来完成这一切。我不确定为什么,因为我没有直接引用道具,但我确实将其内容复制到方法中的变量中。

     updateArray(){
        let updatedArray = []
        let oldArray = [...this.props.array]
        oldArray.forEach(element => {
          if(this.componentArray.indexOf(element) > -1){
            updatedArray.push(element)
          }else{
            let newElement = element
            newElement.destroy = true
            updatedArray.push(newElement)
          }
        })
       return updatedArray 
},

为什么会发生这种情况?除了这个,我的组件中的所有其他元素都可以正常工作。

【问题讨论】:

  • my props is being updated instead of the variables i use in the method ...究竟如何?请准确地描述您的期望和您所看到的......
  • 我只希望 forEach 循环中的“元素”使用新的对象属性进行更新,但它最终会更新道具
  • 所以据我所知,如果它是一个简单的值,我会复制它,但如果它是一个更复杂的值,比如数组和对象,我会引用它,这就是为什么正在发生
  • 没错……

标签: arrays vue.js vuetify.js vue-props


【解决方案1】:

是的,您正在将 this.props.array 数组的 元素 复制到方法本地的新数组中,但鉴于数组的元素是对象,两个数组最后都包含 相同对象(references to the objects

您可以使用扩展运算符let newElement = { ...element } 创建原始元素的浅拷贝 - 这将创建全新的对象并复制原始对象的所有属性。但请注意,如果原始对象的任何属性包含数组/对象,您就会遇到同样的问题......只是向下一级

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2020-09-10
    • 2018-04-22
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多