vue实现左侧楼层导航
Vue实现左侧楼层导航的方法
数据准备
创建一个包含楼层信息的数组,每个楼层对象包含id、名称和对应的DOM元素id。例如:
data() {
return {
floors: [
{ id: 1, name: "楼层1", targetId: "floor1" },
{ id: 2, name: "楼层2", targetId: "floor2" }
],
activeFloor: null
}
}
模板结构
在模板中创建导航列表和对应的楼层区域:
<div class="container">
<div class="nav-wrapper">
<ul class="floor-nav">
<li v-for="floor in floors"
:key="floor.id"
:class="{active: activeFloor === floor.id}"
@click="scrollToFloor(floor)">
{{ floor.name }}
</li>
</ul>
</div>
<div class="content">
<div v-for="floor in floors"
:id="floor.targetId"
class="floor-section">
<h2>{{ floor.name }}</h2>
<!-- 楼层内容 -->
</div>
</div>
</div>
滚动定位功能
实现点击导航跳转到对应楼层的方法:
methods: {
scrollToFloor(floor) {
const element = document.getElementById(floor.targetId)
if (element) {
element.scrollIntoView({ behavior: "smooth" })
this.activeFloor = floor.id
}
}
}
滚动监听
添加滚动事件监听,自动更新当前激活的楼层导航:
mounted() {
window.addEventListener("scroll", this.handleScroll)
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScroll)
},
methods: {
handleScroll() {
const scrollPosition = window.scrollY
this.floors.forEach(floor => {
const element = document.getElementById(floor.targetId)
if (element) {
const offsetTop = element.offsetTop
const offsetHeight = element.offsetHeight
if (scrollPosition >= offsetTop && scrollPosition < offsetTop + offsetHeight) {
this.activeFloor = floor.id
}
}
})
}
}
样式优化
添加基础样式使导航固定并美化:
.container {
display: flex;
}
.nav-wrapper {
position: fixed;
width: 200px;
}
.floor-nav {
list-style: none;
padding: 0;
}
.floor-nav li {
padding: 10px;
cursor: pointer;
}
.floor-nav li.active {
color: #42b983;
font-weight: bold;
}
.floor-section {
min-height: 100vh;
margin-left: 220px;
}
性能优化
对于大量楼层的情况,可以使用节流函数优化滚动事件:
import { throttle } from "lodash"
methods: {
handleScroll: throttle(function() {
// 原有逻辑
}, 100)
}
响应式处理
添加响应式处理,在小屏幕下隐藏导航或改为其他交互方式:
@media (max-width: 768px) {
.nav-wrapper {
display: none;
}
.floor-section {
margin-left: 0;
}
}






