uniapp二级导航栏
实现二级导航栏的基本方法
在UniApp中实现二级导航栏,可以通过<scroll-view>结合自定义样式或使用官方组件完成。以下是一个基础实现示例:
<template>
<view>
<!-- 一级导航 -->
<scroll-view scroll-x class="nav-primary">
<view
v-for="(item, index) in primaryList"
:key="index"
:class="['primary-item', currentPrimary === index ? 'active' : '']"
@click="switchPrimary(index)"
>
{{item.name}}
</view>
</scroll-view>
<!-- 二级导航 -->
<scroll-view scroll-x class="nav-secondary">
<view
v-for="(subItem, subIndex) in secondaryList"
:key="subIndex"
:class="['secondary-item', currentSecondary === subIndex ? 'active' : '']"
@click="switchSecondary(subIndex)"
>
{{subItem.name}}
</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
primaryList: [
{name: '分类1', subItems: [{name: '子类1'}, {name: '子类2'}]},
{name: '分类2', subItems: [{name: '子类3'}, {name: '子类4'}]}
],
currentPrimary: 0,
currentSecondary: 0,
secondaryList: []
}
},
created() {
this.secondaryList = this.primaryList[0].subItems
},
methods: {
switchPrimary(index) {
this.currentPrimary = index
this.secondaryList = this.primaryList[index].subItems
this.currentSecondary = 0
},
switchSecondary(index) {
this.currentSecondary = index
}
}
}
</script>
<style>
.nav-primary, .nav-secondary {
white-space: nowrap;
background-color: #f8f8f8;
}
.primary-item, .secondary-item {
display: inline-block;
padding: 10px 15px;
}
.active {
color: #007AFF;
border-bottom: 2px solid #007AFF;
}
</style>
使用UI组件库优化
推荐使用uni-ui或第三方UI库简化开发:

-
安装
uni-ui:npm install @dcloudio/uni-ui -
使用分段器组件:

<template> <view> <uni-segmented-control :current="currentPrimary" :values="primaryItems" @clickItem="onClickPrimary" /> <uni-segmented-control :current="currentSecondary" :values="secondaryItems" @clickItem="onClickSecondary" /> </view> </template>
动态加载二级导航数据
通过接口动态获取导航数据更符合实际场景:
async loadNavData() {
const res = await uni.request({
url: 'https://api.example.com/navigation'
})
this.primaryList = res.data.primary
this.secondaryList = this.primaryList[0].children
}
样式优化技巧
添加滑动动画效果:
.nav-secondary {
transition: all 0.3s ease;
}
.secondary-item {
transition: color 0.2s;
}
注意事项
- 在小程序端需注意
scroll-view的横向滚动需设置enable-flex属性(微信小程序) - H5端可能需要额外处理滚动条样式隐藏
- 考虑添加加载状态处理异步数据场景
- 高亮状态建议使用CSS变量实现主题色统一管理






