首页 > 解决方案 > 无需更改即可触发道具监视

问题描述

在我的组件中,我有一个道具 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;
}

为什么 ?

我已经从各个角度查看了我的应用程序。模板中没有任何内容,也没有其他方法可以从父项更新道具。

标签: javascriptvue.jsvuejs2vue-component

解决方案


通过这样做this.Y = this.X;,您正在引用XY并且任何影响的更改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


推荐阅读