vue实现电梯导航
Vue 实现电梯导航
电梯导航(滚动定位导航)常见于长页面,帮助用户快速跳转到对应章节。以下是基于 Vue 的实现方法:
监听滚动与高亮当前章节
通过 IntersectionObserver 监听章节元素是否进入视口,动态更新导航高亮状态:

// 组件脚本部分
export default {
data() {
return {
sections: ['section1', 'section2', 'section3'],
activeSection: ''
}
},
mounted() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.activeSection = entry.target.id;
}
});
}, { threshold: 0.5 });
this.sections.forEach(id => {
const el = document.getElementById(id);
if (el) observer.observe(el);
});
}
}
平滑滚动到对应位置
使用 scrollIntoView 实现平滑滚动:

<!-- 模板部分 -->
<nav>
<ul>
<li
v-for="section in sections"
:key="section"
:class="{ active: activeSection === section }"
@click="scrollTo(section)"
>
{{ section }}
</li>
</ul>
</nav>
methods: {
scrollTo(id) {
const el = document.getElementById(id);
if (el) el.scrollIntoView({ behavior: 'smooth' });
}
}
添加防抖优化
避免滚动事件频繁触发计算:
import { debounce } from 'lodash';
export default {
methods: {
handleScroll: debounce(function() {
// 滚动处理逻辑
}, 100)
}
}
动态生成导航结构
根据页面内容自动生成导航项:
mounted() {
this.sections = Array.from(document.querySelectorAll('[data-section]'))
.map(el => el.id);
}
注意事项
- 确保章节元素具有唯一ID
- 移动端需考虑触摸事件兼容性
- 对于SSR应用需在客户端才执行DOM操作
- 可通过CSS
scroll-behavior: smooth增强兼容性
完整实现可结合Vue自定义指令优化,将滚动逻辑封装为可复用的指令。






