Creating local copy of passed props in child component in vue.js?

前端 未结 1 1643
一生所求
一生所求 2020-12-31 11:25

In vue.js what is the right way to edit prop without changing parent data? What I mean by that is whenever we pass any property from parent to child in vue.js then if we mak

相关标签:
1条回答
  • 2020-12-31 11:37

    In your fiddle, the child component is using Object.assign() to create a copy of data, which is an array of objects. However, this only creates a shallow copy, so the array elements would still refer to the original instances, leading to the behavior you're seeing.

    A few solutions to deep copy the array:

    • Use JSON.parse(JSON.stringify(this.data)), which works reasonably well for objects of strings and numbers:

      data() {
        return {
          local_data: JSON.parse(JSON.stringify(this.data))
        }
      }
      

      (demo 1)

    • Map the objects into new ones:

      data() {
        return {
          local_data: this.data.map(x => ({...x}))
        }
      }
      

      (demo 2)

    • Use a utility library, such as lodash's cloneDeep

      data() {
        return {
          local_data: _.cloneDeep(this.data)
        }
      }
      

      (demo 3)

    0 讨论(0)
提交回复
热议问题