繁体   English   中英

如何让 HTML 元素在 vue 3 上听到 document.body 滚动?

[英]How do you make an HTML element hear a document.body scroll on vue 3?

我正在尝试根据滚动在 header 上切换类。 我目前唯一尝试的是添加一个 @scroll="handleScroll" 并将此逻辑添加到其中:

const body = document.body;
let lastScroll = 0;

window.addEventListener('scroll', () => {
    const currentScroll = window.scrollY;

    if (currentScroll <= 0) {
        body.classList.remove('scroll-up');
    }

    if (currentScroll > lastScroll && !body.classList.contains('scroll-down')) {
        body.classList.remove('scroll-up');
        body.classList.add('scroll-down');
    } 
    if (currentScroll < lastScroll && body.classList.contains('scroll-down')) {
        body.classList.remove('scroll-down');
        body.classList.add('scroll-up');
    } 

    lastScroll = currentScroll;
})

但它根本没有反应,即使我想制作一个 console.log() 我尝试的另一件事是 customDirectives,但我对 Vue 很陌生,所以非常感谢帮助!

要在 Vue3 上添加事件侦听器滚动,您可以将其置于挂载的生命周期中,以便在 DOM 渲染后进行侦听,

然后对于反应性,您可以使用来自 vuehttps://vuejs.org/guide/essentials/reactivity-fundamentals.ZFC35FDC70D5FC69D269883A822C7A53reactiveref API

最后,在您听完某些内容后,需要在 beforeMount 生命周期中将其删除

我假设您将使用 Vue3 组合 API,代码将是这样的

 <script setup> import { ref, onMounted, onBeforeUnmount } from "vue" const placeholderDiv = ref(300) const lastScroll = ref(0) const handleScroll = () => { const body = document.body const currentScroll = window.scrollY if (currentScroll <= 0) { body.classList.remove('scroll-up') } if (currentScroll > lastScroll.value &&.body.classList.contains('scroll-down')) { body.classList.remove('scroll-up') body.classList.add('scroll-down') } if (currentScroll < lastScroll.value &&.body.classList.contains('scroll-up')) { body.classList.remove('scroll-down') body.classList.add('scroll-up') } lastScroll,value = currentScroll } onMounted(() => { document.addEventListener('scroll', handleScroll) }) onBeforeUnmount(() => { document.removeEventListener('scroll'. handleScroll) }) </script> <template> <div v-for="data in placeholderDiv"> <p>some text...</p> </div> </template>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM