gpt4 book ai didi

javascript - Vue 观察类变化

转载 作者:行者123 更新时间:2023-11-28 12:14:19 24 4
gpt4 key购买 nike

我想听听类(class)变化。如果按钮“完全在视口(viewport)中”,则触发点击。 $( "button.in-viewport.complete-in-viewport").trigger( "click"); 找到了许多其他选项,但没有任何类别更改。请问有什么建议吗?

最佳答案

您可以使用MutationObserver观察类的变化,并根据新的类值使用react:

  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 来观察 ref 元素的 class 属性的更改,该属性将调用上面定义的方法:

    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>

关于javascript - Vue 观察类变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52779932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com