微信小程序树结构选择组件(优化源码)

这篇具有很好参考价值的文章主要介绍了微信小程序树结构选择组件(优化源码)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

实现效果:

微信小程序树形结构,微信小程序,小程序 

 

1.index.html

<view wx:for="{{tree}}" wx:key="id" class="tree_container">
  <!-- 一级菜单 -->
  <view style="margin-left: {{treeListIndex*40}}rpx" class="tree-item">
    <view class="tree-item-onOff" wx:if="{{item.children && item.children.length > 0}}" bindtap="isOpen" data-index="{{index}}">
      <image src="../../image/zhankai.svg" class="{{item.open ? 'expand' : 'collapse'}}" />
    </view>
    <view class="tree-item-onOff" wx:else>
    </view>
    <view class="tree-item-name" bindtap="select" data-item="{{item}}" data-index="{{index}}">
      <image wx:if="{{item.checked == 1}}" src="../../image/choice.svg" class="check-box"></image>
      <image wx:if="{{item.checked == 0||item.checked==-1}}" src="../../image/unchoice.svg" class="check-box"></image>
      <text class="tree-item-title {{item.checked === 1 ? 'tree-item-name-select' : '' }}">{{item.name}}</text>
    </view>
  </view>
  <!-- 二级菜单 -->
  <tree wx:if="{{item.children && item.children.length > 0 && item.open }}" data-parent="{{item}}" dataTree='{{ item.children }}' isOpenAll="{{isOpenAll}}" treeListIndex="{{treeListIndex+1}}" catch:select="handleSelect" />
</view>

2.index.js

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    dataTree: {
      type: Array,
      value: []
    },
    checkrule: {
      type: Array,
      value: []
    },
    treeListIndex: { // 当期树形列表的索引
      type: Number,
      value: 1
    },
    isOpenAll: { // 是否展开全部节点
      type: Boolean,
      value: false
    }
  },
  observers: {
    'dataTree': function (params) {
      var arr=[]
      if(this.properties.checkrule.length>0){
        this.setData({
          allChoiceIdList:this.properties.checkrule
        })
        arr = this.showcheck(params)
      }else{
        arr=params
      }
      this.setData({
        tree: this._initSourceData(arr),
      })
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    tree: [],
    allChoiceIdList: [] // 所有选中的id数组
  },
  /**
   * 组件的方法列表
   */
  methods: {
    isOpen(e) {
      const open = 'tree[' + e.currentTarget.dataset.index + '].open'
      this.setData({
        [open]: !this.data.tree[e.currentTarget.dataset.index].open
      })
    },
    _initSourceData(nodes) {
      nodes.forEach(element => {
        if (element.checked === undefined) element.checked = 0
        element.open = this.properties.isOpenAll // 是否展开
        if (element.children && element.children.length > 0) element.children = this._initSourceData(element.children)
      })
      return nodes


    },
    // 选择
    select(e) {
      let item = e.currentTarget.dataset.item
      item = this._handleClickItem(item)
      console.log('当前节点:', item)
      this.data.tree = this._updateTree(this.data.tree, item)
      this.setData({
        tree: this.data.tree
      })
      this.data.allChoiceIdList = this.getAllChoiceId(this.data.tree)
      this.triggerEvent('select', { item: item, idList: this.data.allChoiceIdList }, { bubbles: true, composed: true })
      this.triggerEvent('clickItem', { item: item }, { bubbles: true, composed: true })
    },
    // 选择冒泡事件
    handleSelect(e) {
      let parent = e.currentTarget.dataset.parent
      let currentTap = e.detail.item
      console.log('parent节点:', parent)
      // 修正它的父节点
      parent.children = this._updateTree(parent.children, currentTap)
      const { half, all, none } = this.getChildState(parent.children)
      // console.log(`half:${half},all:${all},none:${none}`)
      if (half) parent.checked = -1
      if (all) parent.checked = 1
      if (none) parent.checked = 0
      // 修正整个tree
      this.data.tree = this._updateTree(this.data.tree, parent)
      this.setData({
        tree: this.data.tree
      })
      this.data.allChoiceIdList = this.getAllChoiceId(this.data.tree)
      this.triggerEvent('select', { item: parent, idList: this.data.allChoiceIdList }, { bubbles: true, composed: true })
    },
    /**
     * @method 处理点击选择
     * @param {Object} node 节点对象
     * @returns {Object} node 处理完毕的节点
     * @description 有子节点则全选中或全取消,当前为最底层单节点则选中或单取消
     */
    _handleClickItem(node) {
      switch (node.checked) {
        case 0:
          node.checked = 1
          if (node.children && node.children.length > 0) node.children = this._allChoice(node.children)
          break;
        case 1:
          node.checked = 0
          if (node.children && node.children.length > 0) node.children = this._allCancel(node.children)
          break;
        default:
          node.checked = 1
          if (node.children && node.children.length > 0) node.children = this._allChoice(node.children)
          break;
      }
      return node
    },
    /**
     * @method 全选
     * @param {Array} nodes 节点数组
     * @returns {Array} nodes 处理完毕的节点数组
    */
    _allChoice(nodes) {
      if (nodes.length <= 0) return
      for (let i = 0; i < nodes.length; i++) {
        nodes[i].checked = 1
        if (nodes[i].children && nodes[i].children.length > 0) nodes[i].children = this._allChoice(nodes[i].children)
      }
      return nodes
    },
    /**
     * @method 全取消
     * @param {Array} nodes 节点数组
     * @returns {Array} nodes 处理完毕的节点数组
    */
    _allCancel(nodes) {
      if (nodes.length <= 0) return
      for (let i = 0; i < nodes.length; i++) {
        nodes[i].checked = 0
        if (nodes[i].children && nodes[i].children.length > 0) nodes[i].children = this._allCancel(nodes[i].children)
      }
      return nodes
    },
    /**
     * @method 更新tree
     * @param {Array} tree 节点树
     * @param {Object} newItem 需要替换新节点
     * @description 找到tree中目标进行替换
     */
    _updateTree(tree, newItem) {
      if (!tree || tree.length <= 0) return
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === newItem.id) {
          tree[i] = newItem
          break
        } else {
          if (tree[i].children && tree[i].children.length > 0) {
            tree[i].children = this._updateTree(tree[i].children, newItem)
          }
        }
      }
      return tree
    },
    /**
     * @method 获取子节点的状态
     * @param {Array} node 节点数组
     */
    getChildState(node) {
      let all = true;
      let none = true;
      for (let i = 0, j = node.length; i < j; i++) {
        const n = node[i];
        if (n.checked === 1 || n.checked === -1) {
          none = none && false;
        }
        if (n.checked === 0 || n.checked === -1) {
          all = all && false
        }
      }
      return { all, none, half: !all && !none };
    },
    // 获取所有选中的节点id
    getAllChoiceId(nodes, res = []) {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].checked === 1) res.push(nodes[i].id)
        if (nodes[i].children && nodes[i].children.length > 0) this.getAllChoiceId(nodes[i].children, res)
      }
      return res
    },

    //回显选中的
    showcheck(nodes) {
        for (let i = 0; i < nodes.length; i++) {
          if (this.properties.checkrule.indexOf(nodes[i].id) > -1) {
            nodes[i].checked = 1
          }
          if (nodes[i].children && nodes[i].children.length > 0) this.showcheck(nodes[i].children)
        }
      return nodes
    },
  }
})

3.index.css

/* modules/attestation/pages/checkrule/index.wxss */
.tree_container {
  width: auto;
  box-sizing: border-box;
  overflow: scroll;
  background: #fff;
}

.tree-item {
  width: auto;
  box-sizing: border-box;
  overflow-x: scroll;
  padding: 10rpx 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.tree-item-name {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex: 8;
}

.tree-item-title {
  margin-left: 24rpx;
  color: #1c2438;
  font-size: 32rpx;
  word-break: break-all;
}

.tree-item-onOff {
  width: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.collapse {
  width: 36rpx;
  height: 20rpx;
  transform: rotate(-90deg);
}

.expand {
  width: 36rpx;
  height: 20rpx;
}

.check-box {
  height: 32rpx;
  width: 32rpx;
  margin-left: 30rpx;
}

.tree-item-name-select {
  color: #0079FE;
}

4.index.josn

{
  "component": true,
  "usingComponents": {
    "tree": "/index"
  }
}

5.页面引用

  <tree dataTree="{{list}}" id='trees' checkrule='{{roleIds}}' isOpenAll="{{true}}"></tree>

dataTree:树结构数据(数据结构可以源码中修改)

checkrule:回显或设置默认选中的元素文章来源地址https://www.toymoban.com/news/detail-601920.html

到了这里,关于微信小程序树结构选择组件(优化源码)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序自定义日期选择器组件

    默认开始时间为当天 最大结束时间为当天 默认结束时间为开始时间的10后 wxml   js wxss

    2024年02月11日
    浏览(38)
  • 微信小程序,封装身高体重选择器组件

    wxml代码: scrollLeft 保证能选择到最小值和最大值 bounces 关闭ios的回弹效果,回弹之前会有显示复数和大于最大值的情况(也可以不关闭,设置例如:min = valmin?min:val) 6:间隔+刻度的宽度 +1 是额外加一个刻度,这样才完整。 index%5===0: 5的倍数为长刻度,否则为短刻度 wxs代码

    2024年02月12日
    浏览(42)
  • 微信小程序组件 —— 带搜索功能的选择器

    微信小程序组件 —— 带搜索功能的选择器 效果 组件 search-picker 文件 wxml 文件: wxss 文件: 注:/colorui/icon.wxss 文件来自 ColorUI 。 js 文件: 使用 wxml 文件: js 文件: 参考:https://blog.csdn.net/cwin8951/article/details/116160189

    2024年02月16日
    浏览(30)
  • 微信小程序原生写法——24小时时间选择器组件

    使用picker-view来封装成的一个时间选择器 开始时间是当前时间的一个小时之后,秒默认是0秒 可能还有一些情况未处理,后续发现再更新 js文件 第一版:略繁琐 第二版js文件:根据当前时间的时间戳A与24小时之后的时间戳B两者来进行处理获取对应的列表 json文件 wxml文件 wxs

    2024年02月04日
    浏览(37)
  • 微信小程序原生开发功能合集二:下拉选择组件封装

      本章实现小程序中下拉选择组件的封装实现,通过自定义组件的方式实现下拉选择功能,使用小程序的picker组件实现下拉数据的展示及相关自定义处理,封装数据加载过程,数据切换逻辑监听等。   本节实现select组件的开发说明,另使用nodejs创建express服务器,为远程

    2024年02月02日
    浏览(39)
  • 【微信小程序】使用iView组件库的ActionSheet组件实现底部选择功能

    要在微信小程序中使用iView组件库的ActionSheet组件,可以按照以下步骤进行: 首先,确保已经引入了iView组件库的样式和脚本文件。可以在app.wxss中引入iView的样式文件: 同时,在页面的js文件中引入iView的脚本文件: 在需要使用ActionSheet的页面中,可以在wxml文件中添加一个触

    2024年02月16日
    浏览(41)
  • 微信小程序--下拉选择框组件封装,可CV直接使用

            接到的项目需求,查看ui设计图后,由于微信小程序官方设计的下拉选择框不符合需求,而且常用的第三方库也没有封装类似的,所以选择自己自定义组件。在此记录一下,方便日后复用。         ui设计图如下:                   微信官方提供的选择框         对比发现

    2024年02月05日
    浏览(39)
  • 微信小程序 选择学期控件 自定义datePicker组件 不复杂

    我的时间选择组件在common文件夹里 datePicker组件代码 调用的页面:

    2024年02月09日
    浏览(35)
  • 【微信小程序】-- 表单组件 - picker 实现日期选择器(五十三)

    💌 所属专栏:【微信小程序开发教程】 😀 作  者:我是夜阑的狗🐶 🚀 个人简介:一个正在努力学技术的CV工程师,专注基础和实战分享 ,欢迎咨询! 💖 欢迎大家:这里是CSDN,我总结知识的地方,喜欢的话请三连,有问题请私信 😘 😘 😘   大家好,又见面了,

    2023年04月16日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包