Vue注意班级变更

时间:2018-10-12 12:52:11

标签: javascript vue.js vuejs2 event-handling

我想听一堂课的变化。如果按钮“完全在视口中”,则触发单击。 $( "button.in-viewport.fully-in-viewport" ).trigger( "click" ); 发现了许多其他选项,但没有任何更改。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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

  1. 向要观察的元素添加ref

    <button ref="myButton">foo</button>
    
  2. 创建一种方法来处理观察到的更改:

    methods: {
      onClassChange(classAttrValue) {
        const classList = classAttrValue.split(' ');
        if (classList.includes('fully-in-viewport')) {
          console.log('has fully-in-viewport');
        }
      }
    }
    
  3. 创建一个MutationObserver来观察class元素的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();
    }, 
    

Vue.component('foo', {
  template: `<button ref="myButton" class="foo" @click="onClick">foo</button>`,
  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();
  },
  methods: {
    onClassChange(classAttrValue) {
      const classList = classAttrValue.split(' ');
      if (classList.includes('fully-in-viewport')) {
        this.$refs.myButton.click();
      }
    },
    onClick() {
      requestIdleCallback(() => {
        alert('foo clicked');
      });
    }
  }
});

new Vue({
  el: '#app',
  data: () => ({
    active: false
  }),
})
.foo {
  margin: 20px;
}
<script src="https://unpkg.com/vue@2.5.17"></script>

<div id="app">
  <div>
    <label>
      <input type="checkbox" @change="active = !active">
      <code>.fully-in-viewport</code> class
    </label>
  </div>
  <foo :class="{'fully-in-viewport': active}"></foo>
</div>