美文网首页
Vue 树结构多层菜单遍历

Vue 树结构多层菜单遍历

作者: ChenZi_Y | 来源:发表于2020-12-23 15:47 被阅读0次

    记录自己项目使用遍历树菜单方法
    主要使用Vue.extend方法,参考官方API

    模拟树结构数据

        const tree = [
          {
            name: 'it公司',
            child: [
              {
                name: '本级公司'
              },
              {
                name: '人事部',
                child: [
                  {
                    name: '测试1'
                  },
                  {
                    name: '测试2'
                  }
                ]
              },
              {
                name: '行政部'
              },
              {
                name: '销售部'
              }
            ]
          }
        ]
    

    方法

        setListItem(tree) {
          const deepJoinHtml = function(arr) {
            let str = '<ul>'
            arr.forEach(item => {
              const child = item['child']
              let cel = ''
              if (child && Array.isArray(child) && child.length) {
                cel = deepJoinHtml(child)
              }
              str += `<li><div :class="['${cel && `group`}']" @click.stop="${cel ? 'onOpen' : 'onItem'}">${name}</div>${cel}</li>`
            })
            return (str += '</ul>')
          }
          const _comp = Vue.extend({
            methods: {
              onItem() {
                alert('onItem')
              },
              onOpen({target}) {
                const cls = 'active'
                if (target.className.includes(cls)) {
                  target.classList.remove(cls)
                } else {
                  target.classList.add(cls)
                }
              }
            },
            template: deepJoinHtml(tree)
          })
          const el = new _comp().$mount().$el
          this.$nextTick(() => {
            document.querySelector('.emp-list-org__wrap').appendChild(el)
          })
        }
    
    

    相关文章

      网友评论

          本文标题:Vue 树结构多层菜单遍历

          本文链接:https://www.haomeiwen.com/subject/ryxunktx.html