首页 > 解决方案 > 我可以听 $ref 中的 children 属性吗

问题描述

如果一个元素稍后渲染它的子元素并且我有一个元素的引用,我可以监听 children 属性的变化吗?

 <element ref="parent">
    <child-to-be-loaded-later />
 </element>

 watchers: {
    '$refs.parent.children'() {
       // do stuff here 
    }
 }

标签: vue.js

解决方案


您可以在模板 ref 的元素上使用Mutation Observer来监视其子列表:

<template>
  <div>
    <MyList ref="list">
      <li v-for="i in count">item {{ i }}</li>
    </MyList>
  </div>
</template>

<script>
export default {
  async mounted() {
    await this.$nextTick()
    this._observer = new MutationObserver((mutationList) => {
      mutationList.forEach(mutation => {
        if (mutation.type === 'childList') {
          console.log('children added/removed', { added: mutation.addedNodes, removed: mutation.removedNodes})
        }
      })
    })

    this._observer.observe(this.$refs.list.$el, { childList: true })
  },
  beforeUnmount() {
    this._observer.disconnect()
  },
  beforeDestroy() {
    this._observer.disconnect()
  }
}
</script>

演示


推荐阅读