van-tree-select在Vue项目中的使用

在写H5和APP项目时,有时候会用到分类选择列表功能,如图:
在这里插入图片描述

官方文档组件:TreeSelect 分类选择

使用步骤

1.引入组件

可以全局安装Vant组件 然后在main.js中引入 代码如下(示例):

import Vant from 'vant'
import 'vant/lib/index.css'

Vue.use(Vant)

也可以在单独的页面引入 代码如下(示例):

import { TreeSelect } from "vant";

2.使用

html代码部分:

<van-tree-select
  :items="items"
  :active-id.sync="items.activeId"
  :main-active-index.sync="items.activeId"
   @click-nav="onNavClick">
  <template slot="content">  // 通过插槽的形式可以自定义展示的样式
    <div class="m_box"
      v-for="item in tableSelect"
      :key="item.index">
      <img :src="item.tableLogo" alt="">
       <div class="b_content">
         <div class="b_title">{{item.tableName}}</div>
         <div class="b_price">{{item.price}}</div>
       </div>
    </div>
  </template>
</van-tree-select>

js代码:

export default {
  data () {
    return {
      items: [], // 左侧展示的所有分类
      tableAll: [], // 获取所有展示的数据
      tableSelect: [], // 当前分类下的数据
    }
  },
  mounted () {
    this.getTypeList()  // 获取所有分类
    this.getAllTable()  // 获取所有展示的数据
  },
  methods: {
    async getTypeList () {
      const res = await tableTypeList({ page: -1, pageSize: 10 }) // 调用后端接口显示所有分类
      if (res.code === 0) {
        res.data.tables.forEach(v => {
          this.items.push(
            {
              text: v.name,   // items里面的对象属性必须是text和activeId
              activeId: v.id
            }
          )
        })
      }
    },
    async getAllTable () {
      const res = await getAllTable()
      if (res.code === 0) {
        this.tableAll = res.data
      }
    },
    onNavClick (index) {
      const id = this.items[index].activeId // 点击分类传入当前下标获取该分类的ID
      //然后通过id筛选出当前分类下的数据展示到页面中
      this.tableSelect = this.tableAll.filter(v => v.selfTableType.id === id) 
    }
  }
}

如果对以上代码有什么问题可以评论私信!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐