记录自己项目使用遍历树菜单方法
主要使用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)
})
}