uniapp 左右侧菜单联动
时间: 2025-01-02 17:34:19 浏览: 165
### 实现 UniApp 左右菜单联动效果
在 UniApp 中实现左右侧菜单的联动效果可以通过 `scroll-view` 组件来达成。此方法适用于多种平台,包括微信小程序、H5 网页以及 Android 和 iOS 应用程序等[^1]。
#### 效果图展示
通过合理的布局设计,可以创建出类似于美团外卖页面的商品分类视图,在该界面中左侧显示类别列表而右侧则呈现对应类别的具体内容项。当用户点击左边栏中的某个选项时,右边的内容会随之更新;反之亦然——即随着右边内容区域上下滚动浏览不同条目时,左侧面板也会同步高亮当前所处位置对应的标签[^2]。
#### 数据结构准备
为了使这种交互更加直观易懂,通常建议采用如下所示的数据格式:
```json
[
{
"id": 0,
"name": "全部",
"list": [
{"title": "商品A"},
{"title": "商品B"}
]
},
...
]
```
每一条记录代表一个大类及其下属的小类产品集合。这样的组织方式有助于简化后续编程工作量并提高代码可读性和维护性。
#### 页面模板编写 (template)
```html
<template>
<view class="container">
<!-- 左边 -->
<scroll-view scroll-y :style="{height:winHeight+'px'}" @click="handleClickLeftMenu" v-for="(item,index) in menuList" :key="index">
<view :class="['menu-item', currentIndex===index?'active':'']">{{ item.name }}</view>
</scroll-view>
<!-- 右边 -->
<scroll-view scroll-y :style="{height:winHeight+'px'}" ref="rightScroll" @scroll="handleRightScroll">
<block v-for="(category, index) in menuList" :key="index">
<view class="goods-list-title">{{ category.name }}</view>
<view class="goods-list-content">
<view v-for="(goodItem, goodIndex) in category.list" :key="goodIndex">{{ goodItem.title }}</view>
</view>
</block>
</scroll-view>
</view>
</template>
```
这段 HTML 片段定义了两个主要部分:一个是用来放置各个类目的导航链接(左侧),另一个则是具体产品的详情介绍区(右侧)。其中利用了 Vue.js 的双向绑定特性使得两者之间能够相互影响彼此的状态变化。
#### JavaScript 处理逻辑 (js)
```javascript
export default {
data() {
return {
winHeight: '', // 屏幕高度
menuList: [], // 菜单数据源
currentIndex: 0, // 当前选中的索引值,默认为第一个元素
};
},
onLoad(options){
this.getSystemInfo();
this.loadGoodsData();
},
methods:{
getSystemInfo(){
const systemInfo = uni.getSystemInfoSync();
this.winHeight = systemInfo.windowHeight;
},
loadGoodsData(){
// 假设这里是从服务器获取到了商品信息,并将其赋给data里的menuList变量
this.menuList=[
{ id: 0,name:"全部", list:[{ title:'商品A'},{ title:'商品B'}]},
...];
},
handleClickLeftMenu(e){
let index=e.currentTarget.dataset.index;
this.currentIndex=index;
setTimeout(() => {
this.scrollToCurrentCategory(index);
}, 10);
},
handleRightScroll(event){
var scrollTop=event.detail.scrollTop;
for(let i=0;i<this.menuList.length;i++){
if(scrollTop>=this.$refs.rightScroll.children[i].offsetTop-this.winHeight*0.7 && scrollTop<=this.$refs.rightScroll.children[i+1]?.offsetTop-this.winHeight*0.7){
this.currentIndex=i;
break;
}
}
},
scrollToCurrentCategory(index){
try{
this.$nextTick(()=>{
this.$refs.rightScroll.scrollTo({
top:this.$refs.rightScroll.children[index].offsetTop-(this.winHeight)*0.3,
duration:300
});
})
}catch(error){}
}
}
}
```
上述脚本实现了几个核心功能:
- 获取设备屏幕尺寸以适应不同的终端环境;
- 加载初始的产品分类及明细资料;
- 用户触碰左侧栏目触发事件处理函数改变当前激活状态的同时让右侧内容平滑过渡至指定位置;
- 监听右侧容器内的滚动行为从而动态调整左侧高亮指示器的位置。
阅读全文
相关推荐















