观察 Vue 中 DOM 子级的数量

bla*_*laz 4 observable vue.js

给定一个典型的 Vue 组件及其slot用法:

<template>
  <div>
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "VueComponent"
}
</script>
Run Code Online (Sandbox Code Playgroud)

有没有可能的方法来实现一个观察者/观察者来跟踪内部 DOM 子元素的数量slot?我需要知道何时在组件内添加/删除子项。

bla*_*laz 5

所以我发现对我的问题有用的是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>
Run Code Online (Sandbox Code Playgroud)

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