How to $set a property to multiple objects in an array but have retain individual reactivity in vue js

前端 未结 1 754
萌比男神i
萌比男神i 2021-01-22 09:37

In my case, I have data array with multiple objects

data() {
 return {
   selected: 0,
   presetData: [true, true, true],
   data: [
     {
       na         


        
1条回答
  •  佛祖请我去吃肉
    2021-01-22 10:04

    This is an object reference issue. Each of your time properties references the same array (presetData). You can break out of this problem by making shallow copies via spread syntax.

    You can also avoid Vue.set() when assigning new data using the same technique

    setNewData() {
      this.data = this.data.map(d => ({
        ...d, // create a shallow copy of each data item
        time: [...this.presetData] // add "time" as a shallow copy of presetData
      }))
    },
    

    To change individual array elements within the time property, you need to continue using Vue.set(), ie

    this.$set(item.time, selected, true)
    

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