javascript - Prop watch 触发无变化

标签 javascript vue.js vuejs2 vue-component

在我的组件中,我有一个 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/

相关文章:

javascript - 使用 vue js 多选动态更改选项

vue.js - 将 prop 传递给 vuejs mixin 但属性未定义

javascript - 在 v-for 列表项中显示和隐藏 div (Vue.js 2)

javascript - 使用 TypeScript 在代理中正确键入动态函数

javascript - window.pageYOffset 与 IE11 上的 window.scrollY

javascript - 更改 Windows 中的文本选择方法

vue.js - 无法将 tailwind headless ui 与 vue 2 一起使用。对象(...)不是函数

javascript - 为什么将 componentDidMount 更改为非箭头功能会使热重载再次起作用?

javascript - 如何在方法中使用的 vue apollo 查询中重新获取/更新结果

javascript - 为什么在浏览器中不显示任何内容? (vue.js 2)