vue2 监听dom属性的变化
在Vue 2中,可以使用指令来监听DOM属性的变化。以下是一个示例:
<template>
<div>
<input type="text" v-model="message">
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: '',
};
},
directives: {
observe: {
inserted(el, binding) {
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === binding.value) {
binding.expression && this[binding.expression] = el.getAttribute(binding.value);
}
}
});
observer.observe(el, { attributes: true });
},
},
},
mounted() {
this.$nextTick(() => {
this.$el.querySelectorAll('[v-observe]').forEach((el) => {
const attr = el.getAttribute('v-observe');
el.setAttribute(attr, this[attr]);
});
});
},
};
</script>
在上述示例中,我们定义了一个自定义指令v-observe,通过inserted钩子函数使用MutationObserver来监听DOM属性的变化。当DOM属性发生变化时,我们可以通过binding.value来获取指令的绑定值,然后将其赋值给相应的data属性。
在组件的mounted钩子函数中,我们使用this.$el.querySelectorAll('[v-observe]')来获取所有带有v-observe属性的DOM元素,然后通过setAttribute将指令的绑定值赋给对应的DOM属性。
这样,当DOM属性发生变化时,相应的data属性也会更新
原文地址: https://www.cveoy.top/t/topic/iHAL 著作权归作者所有。请勿转载和采集!