Vue3实现鼠标滚动切换一屏,直接上代码,section中可直接使用<component> <component/>
动态渲染组件
<script setup>
import { ref, onMounted, watch } from 'vue'
import _ from 'loadsh'
const sections = ref([
{
title: 'Banner',
id: 'section0',
component: ''
},
{
title: '第一屏',
id: 'section1',
component: ''
},
{
title: '第二屏',
id: 'section2',
component: ''
},
{
title: '第三屏',
id: 'section3',
component: ''
},
{
title: '第四屏',
id: 'section4',
component: ''
},
{
title: '第五屏',
id: 'section5',
component: ''
},
{
title: '第六屏',
id: 'section6',
component: ''
}
])
const section = ref()
const wheelIndex = ref(0)
const handleWheel = (event) => {
event.preventDefault();
handleScroll(event)
}
const handleScroll = _.debounce((event) => {
if (event.deltaY > 0) {
if (wheelIndex.value >= 6) return
wheelIndex.value += 1
}
if (event.deltaY < 0) {
if (wheelIndex.value <= 0) return
wheelIndex.value -= 1
}
}, 500)
watch(wheelIndex, (n, o) => {
if (!section.value[wheelIndex.value]) return
window.scrollTo({
top: section.value[wheelIndex.value].offsetTop,
behavior: 'smooth'
})
})
onMounted(() => {
window.addEventListener('wheel', handleWheel, { passive: false })
})
</script>
<template>
<div class="container" ref="container">
<section class="section" ref="section" v-for="(item, index) in sections" :key="index">{{ item.title }}</section>
</div>
</template>
<style scoped>
body {
overflow: hidden;
}
::-webkit-scrollbar {
width: 0 !important;
display: none;
overflow: hidden;
}
.section {
height: 100vh;
}
</style>