我正在尝试使用 Vue3 在滚动时制作粘性标题;但我现在卡住了。
这是我的模板:
<template>
<div @scroll="handleFoo" class="foo" ref="fooHeader">
<slot/>
</div>
</template>
这是我的代码
methods: {
handleFoo() {
const fooHeader = this.$refs.fooHeader as HTMLElement;
const sticky = fooHeader.offsetTop;
console.log(fooHeader);
window.pageYOffset > sticky) ? fooHeader.classList.add('sticky') : fooHeader.classList.remove('sticky');
},
},
mounted() {
this.$nextTick(() => {
window.addEventListener('scroll', this.handleFoo);
});
},
我还需要 unmounted(),但我无法使这个工作正常。如果我使用@click,它会正确记录 fooHeader 的 console.log。
我将此组件用作更大视图的一部分;所以我想我并没有真正滚动浏览这个 foo 组件,但也在父组件上尝试了这种方法,但没有奏效。
有人可以帮我吗?
谢谢!