vue.js - 我可以听 $ref 中的 children 属性吗
问题描述
如果一个元素稍后渲染它的子元素并且我有一个元素的引用,我可以监听 children 属性的变化吗?
<element ref="parent">
<child-to-be-loaded-later />
</element>
watchers: {
'$refs.parent.children'() {
// do stuff here
}
}
解决方案
您可以在模板 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>
推荐阅读
- r - 删除带括号的字符串
- scala - 有没有办法在 Play Framework 中翻译动态文本?
- html - div 元素上的样式应用于 div 内的按钮
- python - 将 RGB 深度图与没有内在矩阵的 RGB 图像对齐
- uikit - 我们如何在 UIStackview 中的两个视图之间创建一个具有自动宽度的间隔视图?
- python - 为什么 plot_model 会引发显示此神经网络的断言错误?
- python - 如何从缓冲区加载图像以进行预测?
- swift - UITableViewCell 中快速、模糊的图像运行不流畅
- ruby-on-rails - 图像未在 rails 6 视图中显示
- css - css input[type=radio] 在 IE 11 上无法正常工作