Vue 观察类变化

xx5*_*5ko 6 javascript event-handling vue.js vuejs2

我想听听班级变化。如果按钮获得“完全在视口中”,则触发点击。$( "button.in-viewport.fully-in-viewport" ).trigger( "click" ); 找到了许多其他选项,但与班级变化无关。请问有什么建议吗?

ton*_*y19 19

您可以使用 aMutationObserver来观察类的变化,并根据新的类值做出反应:

  1. ref给元素添加a进行观察:

    <button ref="myButton">foo</button>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建一个方法来处理观察到的变化:

    methods: {
      onClassChange(classAttrValue) {
        const classList = classAttrValue.split(' ');
        if (classList.includes('fully-in-viewport')) {
          console.log('has fully-in-viewport');
        }
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 创建一个MutationObserver观察元素class属性变化的a ,ref它将调用上面定义的方法:

    mounted() {
      this.observer = new MutationObserver(mutations => {
        for (const m of mutations) {
          const newValue = m.target.getAttribute(m.attributeName);
          this.$nextTick(() => {
            this.onClassChange(newValue, m.oldValue);
          });
        }
      });
    
      this.observer.observe(this.$refs.myButton, {
        attributes: true,
        attributeOldValue : true,
        attributeFilter: ['class'],
      });
    },
    beforeDestroy() {
      this.observer.disconnect();
    }, 
    
    Run Code Online (Sandbox Code Playgroud)

<button ref="myButton">foo</button>
Run Code Online (Sandbox Code Playgroud)
methods: {
  onClassChange(classAttrValue) {
    const classList = classAttrValue.split(' ');
    if (classList.includes('fully-in-viewport')) {
      console.log('has fully-in-viewport');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
mounted() {
  this.observer = new MutationObserver(mutations => {
    for (const m of mutations) {
      const newValue = m.target.getAttribute(m.attributeName);
      this.$nextTick(() => {
        this.onClassChange(newValue, m.oldValue);
      });
    }
  });

  this.observer.observe(this.$refs.myButton, {
    attributes: true,
    attributeOldValue : true,
    attributeFilter: ['class'],
  });
},
beforeDestroy() {
  this.observer.disconnect();
}, 
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的高质量回答。对于 Vue 3,请注意,如果您使用 Composition API(您应该这样做,这太棒了),请将 beforeDestroy() 替换为 onBeforeUnmounted(),然后将观察者实例化放在 onMounted() 之外,例如:“constobserver = null”,这样它就可以由 onMounted 和 onBeforeUnmounted 使用。 (4认同)