【问题标题】:Watching for array additions/deletions in Vue在 Vue 中观察数组的添加/删除
【发布时间】:2020-07-24 17:42:27
【问题描述】:

当像这样在 Vue 中观察数组时:

watch: {
  myarray(val) {
    // react to additions or deletions on myarray
  },
},

并像这样在该数组上添加或删除项目:

this.myarray.splice(this.myarray.findIndex((d) => d.id === myId), 1);
this.myarray.push({name: 'New Item'});

如何查看阵列上的这些添加或删除。我可以通过两种方式做到这一点:

  • 使用 v-for 生成(无渲染)组件并使用该组件的 created()/beforeDestroy() 挂钩。
  • 比较新旧版本的数组并找出差异(通过遍历整个数组)

但是这两种方法都会给我的应用程序增加性能开销(这个数组中有多达十万个元素)。
手表回调有什么办法可以给我一个添加或删除的列表。

这里描述的(value, mutation) 回调:https://optimizely.github.io/vuejs.org/api/instance-methods.html 正是我需要的。不幸的是,这似乎不再起作用了。

【问题讨论】:

  • 使用Vue.set(...)vm.$set(...)添加一个元素,使用Vue.delete(...)vm.$delete(...)删除一个元素。
  • 如何添加和删除该数组中的元素?请阅读stackoverflow.com/help/minimal-reproducible-example 并提供代码,以便您的情况可以理解。
  • 嗨,有没有办法让你获取要删除的元素的索引,然后你可以这样做 data() { return { indexOfObjectDeleted: 0, } this.indexOfObjectDeleted = ... ...;观看:{ myarray(newValOfArray, oldValueOfArray) { const valueOfObjectDeleted = oldValueOfArray[this.indexOfObjectDeleted] }, },
  • 很遗憾不是,数组是来自父组件的prop,我什至不知道数组上是否删除或添加了任何东西。
  • @crs,可以传递isArrayDeletedindexOfArrayDeleted等props。来自父组件。

标签: vue.js


【解决方案1】:

到目前为止,我想出的最好的方法是覆盖数组的 push 和 splice 方法。不过我不太喜欢这个解决方案,因为它没有使用 Vue 的内置反应性,这与我在这里所做的基本相同:

created() {
  this.myarray.push = (...args) => {
    //do something with args
    return Array.prototype.push.apply(this.myarray, args);
  };
  this.myarray.splice = (...args) => {
    //do something with args
    return Array.prototype.splice.apply(this.myarray, args);
  };
  //any more array methods you want to intercept
},

另外,如果您不需要使用 push()splice() 的现有代码来与此兼容,您当然可以定义新函数,例如 push2()splice2() 以避免覆盖本机函数.

或者您可以在组件本身上定义这样的函数来充当数组的设置器。

请注意,当使用上面的 sn-p 时,您会失去 Vues 自己对该数组的反应性。要保留两者,您必须这样做:

created() {
  const originalPush = this.myarray.push;
  const originalSplice = this.myarray.splice;
  this.myarray.push = (...args) => {
    //do something with args
    return originalPush.apply(this.myarray, args);
  };
  this.myarray.splice = (...args) => {
    //do something with args
    return originalSplice.apply(this.myarray, args);
  };
  //any more array methods you want to intercept
},

【讨论】:

    猜你喜欢
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多