vue.js - 在 Vue 中观察/观察 DOM 子级的数量

标签 vue.js observable

给定一个带有 slot 用法的典型 Vue 组件:

<template>
  <div>
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "VueComponent"
}
</script>

是否有任何可能的方法来实现跟踪 slot 内 DOM 子级数量的观察者/观察者?我需要知道何时在组件内添加/删除子项。

最佳答案

所以我发现对我的问题有用的是 MutationObserver .我们需要在组件挂载后附加一个观察者,添加回调处理程序并在组件销毁(在 Vue3 中卸载)之前断开观察者。

这是一个用 Vue 2.6 编写的工作示例

<template>
  <div ref="container">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "VueComponent",
  data() {
    return {
      observer: null
    }
  },
  mounted() {
    this.initObserver()
  },
  beforeDestroy() {
    if (this.observer) this.observer.disconnect()
  },
  methods() {
    handleChildrenChanged() {

    },
    initObserver() {
      config = {
        subtree: false,
        childList: true,
        // it's better if you can detect children change by id
        // this can reduce number of updates
        // attributes: true,
        // attributeList: [ 'id' ] 
      }
      const self = this
      const callback = () => {
        self.$nextTick(() => {
          self.handleChildrenChanged()
        })
      }
      const observer = new MutationObserver(callback)
      observer.observe(this.$refs.container, config)
      this.observer = observer
    }
  }
}
</script>

您可以在 Vue 中找到 MutationObserver 的另一种用法:https://dev.to/sammm/using-mutationobserver-and-resizeobserver-to-measure-a-changing-dom-element-in-vue-3jpd

关于vue.js - 在 Vue 中观察/观察 DOM 子级的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64733728/

相关文章:

javascript - 错误 : The client-side rendered virtual DOM tree is not matching server-rendered

vue.js - vue如何接管一个预渲染的页面?

angular - 错误响应中断 valueChanges [Angular2]

java - FilteredList 在更新时给出 java.lang.ArrayIndexOutOfBoundsException

javascript - 打印没有预览的表格

javascript - 如何在vuejs中从javascript导出数据?

unit-testing - 如何使用 Vue Test Utils 测试全局事件总线?

带有 Observable 的 Angular *ngif 和来自异步调用的数据

angular - RxJS forkJoin 处理路由解析错误

angular - 单元测试主题 : Cannot read property 'unsubscribe' of undefined