uniapp垂直分类导航
时间: 2025-04-30 20:43:57 浏览: 24
### 垂直分类导航的实现方法
在 UniApp 中,可以通过 `scroll-view` 组件配合动态数据绑定来实现经典的垂直分类导航效果。这种布局通常由两部分组成:左侧固定宽度的菜单栏和右侧滚动的内容区域。当用户点击左侧菜单项时,右侧内容会随之更新并定位到对应的部分。
以下是基于引用中的描述[^1]以及实际开发经验整理的一个完整示例:
#### HTML 结构
```html
<template>
<view class="container">
<!-- 左侧菜单 -->
<scroll-view scroll-y class="left-menu" :style="{ height: windowHeight + 'px' }">
<view v-for="(item, index) in categories" :key="index"
@click="changeCategory(index)"
:class="['menu-item', currentIndex === index ? 'active' : '']">
{{ item.name }}
</view>
</scroll-view>
<!-- 右侧内容 -->
<scroll-view scroll-y class="right-content" :style="{ height: windowHeight + 'px' }">
<view v-for="(category, index) in categories" :key="index" :id="'cate-' + index">
<text>{{ category.name }}</text>
<view v-for="product in category.products" :key="product.id" class="product-item">
{{ product.name }} - ¥{{ product.price }}
</view>
</view>
</scroll-view>
</view>
</template>
```
#### 样式定义
```css
<style>
.container {
display: flex;
}
.left-menu {
width: 200rpx;
background-color: #f7f7f7;
}
.menu-item {
padding: 20rpx;
text-align: center;
border-bottom: 1rpx solid #ddd;
}
.active {
background-color: white;
font-weight: bold;
}
.right-content {
flex: 1;
padding: 20rpx;
}
.product-item {
margin-top: 20rpx;
padding: 10rpx;
border-bottom: 1rpx solid #eee;
}
</style>
```
#### JavaScript 部分
```javascript
<script>
export default {
data() {
return {
categories: [
{ name: "水果", products: [{ id: 1, name: "苹果", price: 5 }, { id: 2, name: "香蕉", price: 3 }] },
{ name: "蔬菜", products: [{ id: 3, name: "白菜", price: 2 }, { id: 4, name: "胡萝卜", price: 4 }] }
],
currentIndex: 0,
windowHeight: 0
};
},
onLoad() {
this.windowHeight = uni.getSystemInfoSync().windowHeight;
},
methods: {
changeCategory(index) {
this.currentIndex = index;
const viewId = "#cate-" + index;
uni.createSelectorQuery()
.select(viewId)
.boundingClientRect(rect => {
if (rect) {
uni.pageScrollTo({
scrollTop: rect.top,
duration: 300
});
}
})
.exec();
}
}
};
</script>
```
此代码实现了如下功能:
- **左侧菜单**:通过 `v-for` 动态渲染类别名称,并设置当前选中状态。
- **右侧内容**:展示具体商品列表,支持按类别的切换显示。
- 使用 `uni.createSelectorQuery()` 方法获取目标节点位置,从而平滑滚动至指定区域。
---
###
阅读全文
相关推荐

















