javascript - 无需更改即可触发道具监视
问题描述
在我的组件中,我有一个道具 X,我将它分配给 created 钩子上的数据 Y,因此我可以和平地改变 Y。两者都是数组。
同时,我在 X 上放了一个手表,所以如果道具发生变化,我可以更新 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;
}
为什么 ?
我已经从各个角度查看了我的应用程序。模板中没有任何内容,也没有其他方法可以从父项更新道具。
解决方案
通过这样做this.Y = this.X;
,您正在引用X
,Y
并且任何影响的更改Y
也会影响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
推荐阅读
- node.js - 开玩笑 mockResolvedValue 返回未定义的多个参数
- python - 如何使用 Psycopg 从 Amazon Redshift 加载列名?
- python - 将未知整数舍入到最高的base10值Python
- python - 如果函数返回多种类型,我可以声明函数返回值吗?
- elixir - 为每个可枚举添加一个计算值
- react-native - Using Baidu Map for react native/expo
- nestjs - NestJS mongoose 文档中的“Cat.name”是什么?
- azure - 在循环中向天蓝色事件中心发出事件
- flask - 如何将录制的视频从 js 获取到我的 Flask 应用程序?
- c - 创建嵌套 If 和 else 定义 C 编程