前段时间公司突然要写小程序,项目中有一个树形控件。我找了很久的插件和框架。没有发现小程序能用的。只能硬着头皮自己写。
老规矩,先贴图
- 为什么要特意强调此图标呢?
- 因为该图标为中间状态。此处是我后期要优化的地方,在下面的代码中还未实现。我有了初步的思考。
我的代码中设定(以网络部为例)- 0 该部门成员全部未选中
- 1 该部门成员全部选中
- -1 该部门成员至少选中一人切少于部门总人员数
好了,下面我们来实现树形结构的全选和零选中状态
- 首先是树形组件的代码
components文件夹下创建tree-select文件夹,选择新建component。命名为index
index.wxml文件
<view id="treeItem">
<block wx:for="{
{treeList}}" wx:key="deptId">
<view class="tree-item" style="margin-left: {
{depth*40}}rpx" data-id="{
{item.deptId}}" data-is-check="{
{item.isCheck}}" catchtap="handleClick" >
<!-- 全选 -->
<view class="iconfont iconxuanzhong" wx:if="{
{item.isCheck == 1}}" style="color: #007AFF" ></view>
<!-- 未选中 -->
<view class="iconfont iconweixuanzhong1" wx:if="{
{item.isCheck == 0}}" style="color:#000" ></view>
</view>
<!-- children -->
<view wx:if="{
{item.children}}">
<tree-select treeList="{
{item.children}}" treeArray="{
{treeArray}}" depth="{
{depth+1}}" catchhandleClick="treeClick" id="treeItem"></tree-select>
</view>
</block>
</view>
树形组件主要用的就是递归。所以上面组件中我在组件中又调用组件自身。通过depth来判断层级关系,来实现数据的缩进。treeList为页面中传进来的人员数据,treeArrary为我清洗数据之后传过来的初始的人员选中状态的数组
index.json*
{
"component": true,
"usingComponenuts": {
"tree-select": "/components/tree-select/index"
}
}
此处要在usingComponenuts中引入组件自身
index.js
/**
* 组件的属性列表
*/
properties: {
treeList: {
type: Array,
value: []
},
depth: {
type: Number,
value: 0
}