微信小程式Tree自定義控制元件實現

小建狗發表於2019-02-11

在微信小程式中實現Tree控制元件

之前在網上搜尋了關於微信小程式tree控制元件的實現,但是發現居然沒有人去做tree控制元件,因此本人下定決心憑藉自己一個多月的自學能力給大家分享一下自己的小成果。
第一步:建立tree自定義控制元件
       **1.建立js檔案treebar.js**
        //獲取應用例項
		const app = getApp()
		Component({
		
		  /**
		   * 元件的屬性列表
		   */
		  properties: {
		    serval: {
		      type: 'String',
		      value: '組線名稱'
		    }
		  },
		
		  /**
		   * 元件的初始資料
		   */
		  data: {
		    treeList:[],
		    treeData: [{ id: 1, parentId: 0, name: "一級選單A", rank: 1, code:'1'},// rank:代表第幾級樹節點;code:代表包含哪些子節點ID;
		      { id: 2, parentId: 0, name: "一級選單B", rank: 1, code: '2' },
		      { id: 3, parentId: 0, name: "一級選單C", rank: 1, code: '3' },
		      { id: 4, parentId: 1, name: "二級選單A-A", rank: 2, code: '1,4' },
		      { id: 5, parentId: 1, name: "二級選單A-B", rank: 2, code: '1,5' },
		      { id: 6, parentId: 2, name: "二級選單B-A", rank: 2, code: '2,6' },
		      { id: 7, parentId: 4, name: "三級選單A-A-A", rank: 3, code: '1,4,7' },
		      { id: 8, parentId: 7, name: "四級選單A-A-A-A", rank: 4, code: '1,4,7,8' },
		      { id: 9, parentId: 8, name: "五級選單A-A-A-A-A", rank: 5, code: '1,4,7,8,9' },
		      { id: 10, parentId: 9, name: "六級選單A-A-A-A-A-A", rank: 6, code: '1,4,7,8,9,10' },
		      { id: 11, parentId: 10, name: "七級選單A-A-A-A-A-A-A", rank: 7, code: '1,4,7,8,9,10,11' },
		      { id: 12, parentId: 11, name: "八級選單A-A-A-A-A-A-A-A", rank: 8, code: '1,4,7,8,9,10,11,12' },
		      { id: 13, parentId: 12, name: "九級選單A-A-A-A-A-A-A-A-A", rank: 9, code: '1,4,7,8,9,10,11,12,13' },
		      { id: 14, parentId: 13, name: "十級選單A-A-A-A-A-A-A-A-A-A", rank: 10, code: '1,4,7,8,9,10,11,12,13,14' },
		    ],
		    index:0,
		    left:40
		  },
		  // 元件建立函式(如果是後臺請求的資料,可以在裡面實現)
		  created: function () {
		    var that = this;    
		    var array = that.treeData();
		    if (array.length > 0) {
		      for (var i=0;i<array.length;i++) {
		        var obj = array[i];
		        var list = that.data.treeList;
		        var index_i = that.data.index;
		        obj["checked"] = true;
		        // 該節點是否開啟
		        obj["open"] = false;
		        list[index_i] = obj;
		        that.setData({
		          treeList: list,
		          index: index_i + 1
		        });
		        if (obj.children != undefined) {
		          that.collectTree(obj.children);
		        }      
		      }
		    }
		  },  
		  ready:function() {
		    var that = this;
		    that.setData({
		      treeList: that.data.treeList
		    });
		  },
		  /**
		   * 元件的方法列表
		   */
		  methods: {
		    collectTree: function (list) {
		      var that = this; 
		      if (list.length > 0) {
		        for (var j = 0; j < list.length; j++) {
		          var list1 = that.data.treeList;
		          var index_i = that.data.index;
		          var obj1 = list[j];
		          obj1["checked"] = false;
		          // 該節點是否開啟
		          obj1["open"] = false;
		          list1[index_i] = obj1;
		          that.setData({
		            treeList: list1,
		            index: index_i + 1
		          });
		          
		          if (obj1.children == undefined) {
		            continue;
		          } else {
		            if (obj1.children.length > 0) {
		              that.collectTree(obj1.children);
		            }
		          }
		        }
		      }
		    },
		    selectNode:function(e){
		      var that = this;
		      var trees = that.data.treeList;
		      for (var i=0;i<trees.length;i++) {
		        var obj = trees[i];
		        if (e.target.id == obj.id) {
		          if (obj.open) {
		            obj["open"] = false;
		            trees[i] = obj;
		            for (var j = i; j < trees.length; j++) {
		              var obj1 = trees[j];
		              if (obj1.code.indexOf(e.target.id) >= 0 && e.target.id != obj1.id) {
		                obj1["checked"] = false;
		                obj1["open"] = false;
		                trees[j] = obj1;
		              }
		            }
		          } else {
		            obj["open"] = true;
		            trees[i] = obj;
		            for (var j = 0; j < trees.length; j++) {
		              var obj1 = trees[j];
		              if (e.target.id == obj1.parentId) {
		                obj1["checked"] = true;
		                trees[j] = obj1;
		              }
		            }  
		          }
		        }
		      }
		      
		      that.setData({
		        treeList: trees
		      });
		      //console.log(that.data.treeList);
		    },
		    // 重新對tree進行迴圈
		    reloadTreeData: function (id) {
		      var that = this;
		      var list = that.data.treeList;
		      if (list.length > 0) {
		        for (var i=0;i<list.length;i++) {
		          var obj = list[i];
		          if (id==obj.parentId) {
		            if (obj.checked) {
		              obj["checked"] = false;
		            } else {
		              obj["checked"] = true;
		            }
		            list[i] = obj;
		            that.setData({
		              treeList: list
		            });
		            that.reloadTreeData(obj.id);
		          } else {
		            list[i] = obj;
		            that.setData({
		              treeList: list
		            });
		          }
		        }
		      }
		    },
		    treeData:function() {
		      var that = this;
		      let cloneData = that.data.treeData;    // 對源資料深度克隆
		      let tree = cloneData.filter((father) => {              //迴圈所有項
		        let branchArr = cloneData.filter((child) => {
		          return father.id == child.parentId      //返回每一項的子級陣列
		        });
		        if (branchArr.length > 0) {
		          father.children = branchArr;    //如果存在子級,則給父級新增一個children屬性,並賦值
		        }
		        return father.parentId == 0;      //返回第一層
		      });
		      return tree     //返回樹形資料
		    }
		  }
		})
		
       **2.建立treebar.json檔案**
       {
		  "component": true,
		  "usingComponents": {}
		}
		
		**3.建立treebar.wxml檔案**
		<view wx:for="{{treeList}}" wx:for-item="item" wx:for-index="idx">
		  <view wx:if="{{item.checked==true}}" style='padding-left:{{40*(item.rank+1)}}rpx' 
		    id='{{item.id}}' bindtap='selectNode'>
		    {{item.name}}
		  </view>
		</view>
		
		**4.建立treebar.wxss檔案**
		.tree-left{
		  padding-left: 40rpx;
		}
		
第二步:在外面引用建立的自定義控制元件
在外面頁面的json檔案中加入以下:
{
  "navigationBarTitleText": "樹型結構",
  "usingComponents": {
    "treebar": "自定義treebar控制元件的路徑"
  }
}
第三步:在外面頁面引入以下程式碼
<view class="page">
  <!--載入自定義元件-->
    <treebar id="treebar">{{treebar}}</treebar> 
</view>


完成以上的所有操作,你就可以看到樹形效果了,祝您成功!
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20190211095522199.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbndlaWppYW4xOA==,size_16,color_FFFFFF,t_70)

相關文章