IT이야기

Vue Watch의 클래스 변경

cyworld 2022. 7. 23. 09:58
반응형

Vue Watch의 클래스 변경

수업 변경을 듣고 싶습니다.풀인뷰포트 $( "button.in-viewport.fully-in-viewport" ).trigger( "click" );다른 많은 옵션에서 찾을 수 있지만 클래스 변경에 대해서는 찾을 수 없습니다.안해주 주실? ???

를 사용하면 클래스 변경을 감시하고 새로운 클래스 값에 따라 대응할 수 있습니다.

  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>

언급URL : https://stackoverflow.com/questions/52779932/vue-watch-for-class-change

반응형