在 Vue 2 中,可以使用自定义指令来监听 DOM 属性的变化。以下是一个使用 v-observe 指令来监听 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 属性也会更新。

Vue 2 监听DOM属性变化:自定义指令 v-observe 示例

原文地址: https://www.cveoy.top/t/topic/qn31 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录