在我的组件中,我有一个 Prop X,我将其分配给创建的钩子(Hook)上的数据 Y,因此我可以和平地改变 Y。 都是数组。
与此同时,我在 X 上放了一个 watch ,这样我就可以在 prop 发生变化时更新 Y。
奇怪的是,每当我使用像 Y.sort() 这样的方法时,我的 watch 语句就会被触发
看起来像这样(非常简单):
props: {
X: Array
},
data: function() {
return {
Y: []
}
},
methods: {
someFunc() {
this.Y.sort() // Triggers X's watch
}
},
watch: {
X (newVal) {
this.Y = newVal;
}
},
created: function() {
this.Y = this.X;
}
为什么?
我已经从各个 Angular 审视了我的应用程序。模板和其他方法中都没有任何内容可以更新来自父级的 prop。
最佳答案
通过执行 this.Y = this.X;
,您将通过 Y
和任何影响 Y 的更改来引用
也会影响 X
X
,因此要避免这种情况,请使用以下解决方案之一:
this.Y = this.X.slice();
或
Object.assign(this.Y,this.X)
JS 示例:
let a = [44, 23, 16, 5, 52, 36]
console.log(a) //print the original a
let b = a;
b.sort((c, d) => {
return c - d
});
console.log(a) //a is sorted however we do not call a.sort(...) method
关于javascript - Prop watch 触发无变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54653889/