微信小程序实现左右列表联动的代码
时间: 2024-05-05 22:20:42 浏览: 7
微信小程序实现左右列表联动的代码可参考以下示例:
wxml部分:
```html
<view class="container">
<view class="left">
<scroll-view scroll-y="{{true}}" scroll-into-view="{{scrollIntoView}}" scroll-with-animation="{{true}}" class="scroll-view-left">
<block wx:for="{{leftList}}" wx:key="index">
<view class="item {{leftIndex == index ? 'active' : ''}}" data-index="{{index}}" bindtap="handleLeftItemTap">{{item}}</view>
</block>
</scroll-view>
</view>
<view class="right">
<scroll-view scroll-y="{{true}}" scroll-into-view="{{scrollIntoView}}" scroll-with-animation="{{true}}" class="scroll-view-right">
<block wx:for="{{rightList[leftIndex].children}}" wx:key="index">
<view class="item" data-index="{{index}}" bindtap="handleRightItemTap">{{item}}</view>
</block>
</scroll-view>
</view>
</view>
```
js部分:
```javascript
Page({
data: {
leftIndex: 0,
scrollIntoView: '',
leftList: ['分类1', '分类2', '分类3'],
rightList: [
{
name: '分类1',
children: ['子分类1', '子分类2', '子分类3']
},
{
name: '分类2',
children: ['子分类4', '子分类5', '子分类6']
},
{
name: '分类3',
children: ['子分类7', '子分类8', '子分类9']
}
]
},
handleLeftItemTap: function(e) {
const index = e.currentTarget.dataset.index;
this.setData({
leftIndex: index,
scrollIntoView: `right-item-${index}-0`
});
},
handleRightItemTap: function(e) {
const index = e.currentTarget.dataset.index;
wx.showToast({
title: `点击了${this.data.rightList[this.data.leftIndex].children[index]}`,
icon: 'none'
});
}
})
```
其中,`leftList` 为左侧列表,`rightList` 为右侧列表,`leftIndex` 为左侧选中的索引,`scrollIntoView` 为滚动到的位置。
在左侧列表中点击某个分类时,将 `leftIndex` 更新为当前索引并将 `scrollIntoView` 更新为对应右侧列表中第一个子分类的 `id`,从而实现左侧列表与右侧列表的联动。
右侧列表中点击某个子分类时,可以触发相应的逻辑操作。