小程序实现无限级树形菜单

效果图:

小程序实现无限级树形菜单_第1张图片

源码地址:https://github.com/dressLz/lz

实现思路:  组件的递归调用

    小程序实现无限级树形菜单_第2张图片

mytree为组件,最主要的在组件的自调用。

   mytree.json

{
  "component": true,
  "usingComponents": {
    "mytree": "../mytree/mytree"
  }
}

mytree.wxml


  
    {{model.text}}
    
  
  

mytree.js

// pages/components/mytree/mytree.js
Component({
  properties: {
    model: Object,
  },
  data: {
    open: false,     //是否展开
    isBranch: false, //是否有子级
  },

  methods: {
    toggle: function (e) {
      if (this.data.isBranch) {
        this.setData({
          open: !this.data.open,
        })
      }
    },
    tapItem: function (e) {
      var itemid = e.currentTarget.dataset.itemid;
      console.log('组件里点击的id: ' + itemid);
      this.triggerEvent('tapitem', { itemid: itemid }, { bubbles: true, composed: true });
    }
  },

  ready: function (e) {
    this.setData({
      isBranch: Boolean(this.data.model.childMenus && this.data.model.childMenus.length),
    });
    console.log(this.data);
  },
})

要引用的页面



  

treeData数据

treeData: {
      text: 'My Tree',
      id: 0,
      childMenus: [
        {
          text: 'Parent 1',
          id: 1,
          childMenus: [
            {
              text: 'Child 1',
              id: 2,
              childMenus: [
                {
                  text: 'Grandchild 1',
                  id: 3,
                },
                {
                  text: 'Grandchild 2',
                  id: 4,
                },
              ]
            },
            {
              text: 'Child 2',
              id: 5,
            }
          ]
        },
        {
          text: 'Parent 2',
          id: 6,
          childMenus: [
            {
              text: 'Child 1',
              id: 7,
            },
            {
              text: 'Child 2',
              id: 8,
            }
          ]
        }
      ]
    },

 

你可能感兴趣的:(微信小程序)