1

Basically I'm doing some sorting on an array which gets its value from a prop, as we know props values wont get changed (or at least that's what I read in docs) but when I do a remove on my array, it effects the prop as well:

props: ['allquestions','getskills'],
data() {
  return {
    getskillsnew: this.getskills,
    searchwindow: true,
    allquestionsnew: this.allquestions,
  }
},
methods: {
  filterop(value){
    for (i = this.allquestionsnew.length - 1; i >= 0; --i) {
      if (this.allquestionsnew[i].lastweek === 0) {
        this.$delete(this.allquestionsnew, i);
      }
      setTimeout(() => {
        this.searchwindow = true;
      }, 1000) 
    }
  }
}

so after the for-loop is done and I check my prop (all questions) it has been cut down to 5 as like as this.allquestionsnew , but i want is that this splice only takes effect on this.allquestionsnew not on the prop!

how can i achieve this? Thanks

Shota Tamura
  • 261
  • 3
  • 12
Pc Monk
  • 75
  • 2
  • 4
  • 24

2 Answers2

2

In JavaScript arrays are passed by reference. From the Vue docs ..

Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect parent state.

To get around this you'll need to create a deep clone of your array. For example ..

data() {
   return {
      getskillsnew:this.getskills,
      searchwindow:true,
      allquestionsnew: JSON.parse(JSON.stringify(this.allquestions)),
   }

},

This will only initialize the allquestionsnew array when the component is created. If you need its value to be updated when the prop changes you can do that with a watcher.

tony19
  • 125,647
  • 18
  • 229
  • 307
Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28
1

It is not a good practice. If you have prop - then you should affect on it through the parent. If you want to set some data equal to you prop, then do it in a lifecycle hook:

created() {
    this.allquestionsnew = [...this.allquestions]
}

As you can see, here I used array destructuring (ES6). This would be much better than you did.

Daniyal Lukmanov
  • 1,149
  • 10
  • 21