首先npm安装依赖
npm install --save-dev less less-loader
npm install --save-dev vue2-org-tree
在main.js中引入并使用
import Vue2OrgTree from 'vue2-org-tree'
Vue.use(Vue2OrgTree);
新建组件中使用
//data中的数据
data(){
return{
dataTree: {
id: 0,
label: "XXX科技有限公司",
children: [
{
id: 2,
label: "产品研发部",
children: [
{
id: 5,
label: "研发-前端"
},
]
},
{
id: 3,
label: "销售部",
children: [
{
id: 7,
label: "销售一部"
},
{
id: 8,
label: "销售二部"
}
]
},
{
id: 4,
label: "财务部"
},
{
id: 9,
label: "HR人事"
}
]
},
horizontal: false,
collapsable: false,
expandAll: true,
labelClassName: "bg-white",
}
},
created(){
this.toggleExpand(this.dataTree, this.expandAll);
},
methods:{
toggleExpand(dataTree, val) {
var _this = this;
if (Array.isArray(dataTree)) {
dataTree.forEach(function(item) {
_this.$set(item, "expand", val);
if (item.children) {
_this.toggleExpand(item.children, val);
}
});
} else {
this.$set(dataTree, "expand", val);
if (dataTree.children) {
_this.toggleExpand(dataTree.children, val);
}
}
},
onExpand(data) {
if ("expand" in data) {
data.expand = !data.expand;
if (!data.expand && data.children) {
this.collapse(data.children);
}
} else {
this.$set(data, "expand", true);
}
},
onNodeClick(e, data) {
// alert(data.label);
},
renderContent(h, data) {
return h('Dropdown', {
attrs: {
trigger: 'click'
},
},[
h('a',{
domProps: {
href: 'javascript:;'
},
on: {
click: () => {
this.showFlag = data.children ? true: false;
}
}
},data.label),
h('DropdownMenu',{
slot: 'list',
},[
h('DropdownItem',{
nativeOn: {
click: () => {
}
}
},'修改机构'),
h('DropdownItem',{
style: {
display: (data.id != 0 && !data.children) ? 'block' : 'none'
},
nativeOn: {
click: () => {
this.$Modal.confirm({
title: '确定要删除吗?',
onOk: () => {
this.$Message.info('删除成功');
//删除成功
},
});
}
}
},'删除机构')
]
)
])
},
}
上面 DropdownMenu
和 DropdownItem 都是iview的组件,利用render函数动态写标签,嵌套解构请参考iview
主要是renderContent方法中编写render函数来实现,对每个不同节点的对应操作。例如删除操作不能是根,不能有子节点。
效果如下