微信小程序三级分类实现:使用 Vant Weapp 组件库封装 van-tree-select
- 在小程序项目中安装 Vant Weapp 组件库
在小程序项目根目录下运行以下命令:
npm install vant-weapp -S --production
- 在需要使用 van-tree-select 组件的页面中引入组件
在需要使用 van-tree-select 组件的页面的 .json 文件中添加以下配置:
{
"usingComponents": {
"van-tree-select": "vant-weapp/dist/tree-select/index"
}
}
- 在页面中使用 van-tree-select 组件
在页面的 .wxml 文件中添加以下代码:
<van-tree-select
bind:change='onChange'
:items='items'
:main-active-index.sync='mainActiveIndex'
:active-id.sync='activeId'
:max='3'
:height='300px'
:render-label='renderLabel'
></van-tree-select>
其中,items 为要展示的分类数据,mainActiveIndex 为选中的一级分类的索引,activeId 为选中的分类的 id,max 为最多可以选中几个分类,height 为组件的高度,renderLabel 为自定义每个节点的显示标签。
- 在页面的 .js 文件中定义数据和方法
定义分类数据:
data: {
items: [
{
text: '分类1',
children: [
{
text: '分类1-1',
children: [
{ id: 1001, text: '分类1-1-1' },
{ id: 1002, text: '分类1-1-2' },
],
},
{
text: '分类1-2',
children: [
{ id: 1003, text: '分类1-2-1' },
{ id: 1004, text: '分类1-2-2' },
],
},
],
},
{
text: '分类2',
children: [
{
text: '分类2-1',
children: [
{ id: 2001, text: '分类2-1-1' },
{ id: 2002, text: '分类2-1-2' },
],
},
{
text: '分类2-2',
children: [
{ id: 2003, text: '分类2-2-1' },
{ id: 2004, text: '分类2-2-2' },
],
},
],
},
],
mainActiveIndex: 0,
activeId: [],
},
定义方法:
methods: {
onChange(event) {
const { detail } = event;
this.setData({
mainActiveIndex: detail.index || 0,
activeId: detail.activeId,
});
},
renderLabel(item) {
return item.text;
},
},
其中,onChange 方法监听组件的 change 事件,更新选中的分类数据,renderLabel 方法用于自定义每个节点的显示标签。
- 页面展示效果

原文地址: https://www.cveoy.top/t/topic/oXxF 著作权归作者所有。请勿转载和采集!