道具价值也被改变

Props value being altered as well

我有一个对话框组件,它有一个 student_list 道具,这个对话框是由观察者触发的,所以基本上,在我的主要组件中,当我增加变量 dialog_watcher++ 时,对话框打开。

student_list 道具包含如下所示的数据:

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

现在在 Dialog 组件中,在我的 watch:{} 挂钩中,我有一个变量 student_list_data,我在其中分配了 student_list 道具的值..

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

现在,在 Dialog 组件中,我有一个按钮,我可以在其中拼接 student_list_data 数组中的一些对象。

_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);
}

现在,当我在我的 vue devtools 中检查时,我注意到不仅 student_list_data 被拼接了,而且 student_list 道具也被拼接了。我到处都检查了,但我没有任何将数据拼接到 student_list 道具的功能。

知道我哪里出错了吗?

您错误地克隆了 student_list。试试这个。

watch: {
    this.student_list_data = [... this.student_list];
}

当使用“=”赋值非原始变量时,引用也会被复制。这可能会导致特定对象分配给的所有变量发生突变。

试试下面的方法。

  1. 可以用JSON.stringify转成字符串再解析成JSON.parse.

     this.student_list_data = JSON.parse(JSON.stringify(this.student_list));
    
  2. 您可以使用展开运算符。

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