当前位置:   article > 正文

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

小程序 树菜单

效果图:

源码地址https://download.csdn.net/download/qq_42205731/19547193

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

    

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

   mytree.json

  1. {
  2. "component": true,
  3. "usingComponents": {
  4. "mytree": "../mytree/mytree"
  5. }
  6. }

mytree.wxml

  1. <view class="ul">
  2. <view class="li-item" bindtap='{{isBranch?"toggle":"tapItem"}}' data-itemid='{{ model.id }}'>
  3. <text>{{model.text}}</text>
  4. <image src="https://open.oss.taozhi.cn/audiobook/asset/read/{{open?'shangla':'xiala'}}.png" class="menu-img" wx:if='{{ isBranch }}' ></image>
  5. </view>
  6. <view style='padding-left: 50rpx;' wx:if='{{ isBranch }}' hidden='{{ !open }}'>
  7. <mytree wx:for='{{ model.childMenus }}' wx:key='id' model='{{ item }}'></mytree>
  8. </view>
  9. </view>

mytree.js

  1. // pages/components/mytree/mytree.js
  2. Component({
  3. properties: {
  4. model: Object,
  5. },
  6. data: {
  7. open: false, //是否展开
  8. isBranch: false, //是否有子级
  9. },
  10. methods: {
  11. toggle: function (e) {
  12. if (this.data.isBranch) {
  13. this.setData({
  14. open: !this.data.open,
  15. })
  16. }
  17. },
  18. tapItem: function (e) {
  19. var itemid = e.currentTarget.dataset.itemid;
  20. console.log('组件里点击的id: ' + itemid);
  21. this.triggerEvent('tapitem', { itemid: itemid }, { bubbles: true, composed: true });
  22. }
  23. },
  24. ready: function (e) {
  25. this.setData({
  26. isBranch: Boolean(this.data.model.childMenus && this.data.model.childMenus.length),
  27. });
  28. console.log(this.data);
  29. },
  30. })

要引用的页面

  1. <!--index.wxml-->
  2. <view>
  3. <mytree model='{{ treeData }}' bind:tapitem='tapItem'></mytree>
  4. </view>

treeData数据

  1. treeData: {
  2. text: 'My Tree',
  3. id: 0,
  4. childMenus: [
  5. {
  6. text: 'Parent 1',
  7. id: 1,
  8. childMenus: [
  9. {
  10. text: 'Child 1',
  11. id: 2,
  12. childMenus: [
  13. {
  14. text: 'Grandchild 1',
  15. id: 3,
  16. },
  17. {
  18. text: 'Grandchild 2',
  19. id: 4,
  20. },
  21. ]
  22. },
  23. {
  24. text: 'Child 2',
  25. id: 5,
  26. }
  27. ]
  28. },
  29. {
  30. text: 'Parent 2',
  31. id: 6,
  32. childMenus: [
  33. {
  34. text: 'Child 1',
  35. id: 7,
  36. },
  37. {
  38. text: 'Child 2',
  39. id: 8,
  40. }
  41. ]
  42. }
  43. ]
  44. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/77102
推荐阅读