vue实现滚屏展示
Vue 实现滚屏展示的方法
使用原生滚动监听
在Vue组件中,可以通过监听窗口的滚动事件来实现滚屏展示效果。结合window.scrollY和元素offsetTop判断当前滚动位置是否到达特定区域。
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const sections = document.querySelectorAll('.section')
sections.forEach(section => {
const rect = section.getBoundingClientRect()
if (rect.top <= window.innerHeight * 0.5) {
section.classList.add('active')
}
})
}
}
CSS部分可以添加过渡效果:
.section {
opacity: 0;
transform: translateY(20px);
transition: all 0.5s ease;
}
.section.active {
opacity: 1;
transform: translateY(0);
}
使用Intersection Observer API
Intersection Observer API更高效,适合现代浏览器,不会造成性能问题。
data() {
return {
observer: null
}
},
mounted() {
this.observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('active')
}
})
}, {
threshold: 0.5
})
document.querySelectorAll('.section').forEach(el => {
this.observer.observe(el)
})
},
beforeDestroy() {
this.observer.disconnect()
}
使用Vue指令封装
可以创建自定义指令实现复用:
Vue.directive('scroll-show', {
inserted(el, binding) {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
el.classList.add(binding.value || 'active')
}
})
observer.observe(el)
el._observer = observer
},
unbind(el) {
if (el._observer) {
el._observer.disconnect()
}
}
})
使用方式:
<div v-scroll-show="'fade-in'">内容</div>
使用第三方库
对于复杂场景,可以考虑以下库:
vue-scrollama:基于Scrollama的Vue封装vue-observe-visibility:简化Intersection Observer使用vue-scrollactive:实现滚动导航高亮
安装示例:
npm install vue-scrollactive
基本使用:
import VueScrollactive from 'vue-scrollactive'
Vue.use(VueScrollactive)
<scrollactive>
<a href="#section1" class="scrollactive-item">Section 1</a>
<a href="#section2" class="scrollactive-item">Section 2</a>
</scrollactive>
全屏滚动实现
如需实现全屏滚动效果,可以使用:
vue-fullpage.js:类似fullPage.js的Vue实现vue-page-transition:添加页面过渡效果
安装示例:
npm install vue-fullpage.js
使用方式:
import VueFullPage from 'vue-fullpage.js'
Vue.use(VueFullPage)
<full-page ref="fullpage" :options="options">
<div class="section">第一页</div>
<div class="section">第二页</div>
</full-page>
data() {
return {
options: {
navigation: true,
anchors: ['page1', 'page2']
}
}
}






