Search code examples
javascriptvue.jsvue-props

Props value being altered as well


I have a dialog component that has a student_list props and this dialog is being triggered by a watcher, So basically, in my main component when I increment variable dialog_watcher++, the dialog opens.

The student_list props contains data which looks like this:

student_list = [
   {id: 1, name: 'John'},
   {id: 2, name: 'Jane'},
   {id: 3, name: 'Jake'},
   {id: 4, name: 'Finn'},
]

Now in the Dialog component, In my watch:{} hook, I have a variable student_list_data where I assigned the value of the student_list props..

watch: {
    let temp = this.student_list;
    this.student_list_data = temp;
}

Now, in the Dialog component, I have a button where I splice some object in the student_list_data array.

_selectStudent(item) {
    //remove the selected student from the array
    const index = this.student_list_data.findIndex(obj => obj.id == item.id);
    this.student_list_data.splice(index, 1);

    //append the selected student to a new array
    this.selected_student.push(item);
}

Now, when I inspect in my vue devtools, I noticed that not only the student_list_data are being spliced, but also the student_list props. I checked everywhere but I dont have any function that splices data to student_list props.

Any idea where I went wrong?


Solution

  • When the non-primitive variables are assigned using "=", the reference will also be copied. This may lead to the mutation for all the variables that a particular object is assigned to.

    Try the following.

    1. You can use JSON.stringify to convert it to string and then parse into JSON.parse.

       this.student_list_data = JSON.parse(JSON.stringify(this.student_list));
      
    2. You can use spread operator.

      this.student_list_data = [...this.student_list_data]