1. 首先,在项目根目录下打开命令行工具,使用 npm 安装 vant-weapp 插件。打开命令行工具,输入以下命令:
npm install vant-weapp -S --production
  1. 在微信开发者工具中,打开项目根目录,找到 app.json 文件,将 'vant-weapp/dist/common/index.wxss' 添加到全局样式中。
"style": [
  "app.wxss",
  "vant-weapp/dist/common/index.wxss"
],
  1. 在需要使用 van-tree-select 的页面或组件中,引入 vant-weapp 的 van-tree-select 组件。
<van-tree-select
  :items='items'
  :main-active-index='mainActiveIndex'
  :active-id='activeId'
  :height='height'
  @item-click='onClickItem'
  @nav-click='onClickNav'
  @main-click='onClickMain'
/>
  1. 在 data 中定义需要使用的数据,包括分类数据和选中的分类数据。
data: {
  items: [
    {
      // 一级分类
      text: '分类1',
      id: 1,
      // 二级分类
      children: [
        {
          text: '分类1-1',
          id: 11,
          // 三级分类
          children: [
            {
              text: '分类1-1-1',
              id: 111
            },
            {
              text: '分类1-1-2',
              id: 112
            }
          ]
        }
      ]
    },
    {
      text: '分类2',
      id: 2,
      children: [
        {
          text: '分类2-1',
          id: 21,
          children: [
            {
              text: '分类2-1-1',
              id: 211
            },
            {
              text: '分类2-1-2',
              id: 212
            }
          ]
        }
      ]
    }
  ],
  mainActiveIndex: 0,
  activeId: 1,
  height: 300,
  selectedItems: []
}
  1. 在 methods 中定义 onClickItem、onClickNav 和 onClickMain 函数来处理用户的选择操作。
methods: {
  onClickItem(event) {
    const { id } = event.currentTarget.dataset;
    const selectedItems = this.selectedItems;
    const index = selectedItems.indexOf(id);
    if (index !== -1) {
      selectedItems.splice(index, 1);
    } else {
      selectedItems.push(id);
    }
    this.selectedItems = selectedItems;
  },
  onClickNav(event) {
    const { index } = event.currentTarget.dataset;
    this.mainActiveIndex = index;
  },
  onClickMain(event) {
    const { index } = event.currentTarget.dataset;
    this.mainActiveIndex = index;
    this.activeId = this.items[index].id;
  }
}
  1. 最后,在页面或组件中显示已选中的分类数据。
<view>
  <view>已选中的分类:</view>
  <view>{{selectedItems}}</view>
</view>
微信小程序使用 Vant Weapp 实现三级分类多选功能

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

免费AI点我,无需注册和登录