(VueJS v3) 我如何观察反应式数组的数组突变(插入、删除、替换)?

发布于 2025-01-11 13:14:36 字数 80 浏览 3 评论 0原文

如何观察反应式数组,以便知道调用 push()splice() 等时插入、删除和替换的内容?

How can I watch a reactive array so that I know what is inserted, removed and replaced when push(), splice(), etc is called?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

書生途 2025-01-18 13:14:36

由于 splice 等不会直接为数组分配新值,因此 Vue 的反应性系统不会接收到更改,并且观察者不会触发。

但是,您可以创建一个复制数组的计算对象,然后观察:

computed: {
  myArray() {
    return this.my_array.slice();
  },
},
data() {
  return {
    my_array: [],
  };
},
watch: {
  myArray(newArray, oldArray) {
    // do stuff
  },
},

演示

Since splice etc doesn't directly assign a new value to the array, Vue's reactivity system won't pick up on the changes and the watcher won't fire.

You can, however, create a computed that copies the array and then watch that:

computed: {
  myArray() {
    return this.my_array.slice();
  },
},
data() {
  return {
    my_array: [],
  };
},
watch: {
  myArray(newArray, oldArray) {
    // do stuff
  },
},

Demo

落在眉间の轻吻 2025-01-18 13:14:36

在 Vue3 上,您可以在脚本上执行此操作

<script setup>
watchEffect(() => { console.log(nameOfYourArray)})
</script>

,或者在 Vue 2 和 Vue3 上使用 Option API,

     Watch: {
      nameofYourArray: {
        deep: true,
        immediate:true,
        handler(newVal,oldVal){
        console.log(newVal)
        }
      }
   }

如果您使用 2 个解决方案,请不要忘记添加深度,否则它将无法在子数组上工作

On Vue3 you can do this on your script

<script setup>
watchEffect(() => { console.log(nameOfYourArray)})
</script>

Or on Vue 2 and Vue3 with Option API

     Watch: {
      nameofYourArray: {
        deep: true,
        immediate:true,
        handler(newVal,oldVal){
        console.log(newVal)
        }
      }
   }

if you use 2 solutions you don't forget to add deep otherwise it won't work on child array

吾性傲以野 2025-01-18 13:14:36

也许这会有所帮助 (deep: true):

watch(() => props.options, updateModelValueInternal, {deep: true});

没有 'deep: true' vue3 不会检测数组 (props.options) 内容的更改。它仅检测“选项”的完全重新分配。使用“deep: true”,您可以推送/unshft/slice 等,正在调用处理程序 updateModelValueInternal。

Maybe that will help (deep: true):

watch(() => props.options, updateModelValueInternal, {deep: true});

Without 'deep: true' vue3 is not detecting changes of array (props.options) content. It detects only complete reassignment of 'options'. With 'deep: true' you can push/unshft/slice etc, the handler updateModelValueInternal is being invoked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文