vue项目使用vue2-org-tree (避免踩坑)
2022-09-15 本文已影响0人
SY
1.效果图
image.png
实现方法
1、安装
# use npm
npm i vue2-org-tree
# use yarn
yarn add vue2-org-tree
2.安装 loader
npm install -D less-loader less
*:官方文档引入样式的时候是导入的 less 文件
3、main.js中引入
import Vue from 'vue'
import Vue2OrgTree from 'vue2-org-tree'
Vue.use(Vue2OrgTree)
// ...
4、组件中使用
template代码
<vue2-org-tree
:data="treeData"
collapsable
:render-content="renderContent"
@on-expand="onExpand"
@on-node-click="NodeClick"/>
数据
data () {
return {
treeData: {
id: '0',
label: "NBA季后赛",
children: [
{
id: '1',
label: "西部球队",
children: [
{
id: '1-1',
label: "勇士"
},
{
id: '1-2',
label: "火箭"
},
{
id: '1-3',
label: "太阳"
},
{
id: '1-4',
label: "小牛"
}
]
},
{
id: '2',
label: "东部球队",
children: [
{
id: '2-1',
label: "热火"
},
{
id: '2-2',
label: "雄鹿"
},
{
id: '2-3',
label: "骑士"
},
{
id: '2-4',
label: "凯尔特人"
}
]
}
]
}
}
},
方法:
created(){
this.toggleExpand(this.treeData,true);
},
methods:{
collapse(list) {
list.forEach((child)=> {
if (child.expand) {
child.expand = false;
}
child.children && this.collapse(child.children);
});
},
onExpand(e,data) {
console.log(data,'data')
if ("expand" in data) {
data.expand = !data.expand;
if (!data.expand && data.children) {
this.collapse(data.children);
}
} else {
this.$set(data, "expand", true);
}
},
toggleExpand(data, val) {
if (Array.isArray(data)) {
data.forEach((item)=> {
this.$set(item, "expand", val);
if (item.children) {
this.toggleExpand(item.children, val);
}
});
} else {
this.$set(data, "expand", val);
if (data.children) {
this.toggleExpand(data.children, val);
}
}
},
NodeClick(e,data){
console.log(e)
// e 为 event
console.log(data)
// 当前项的所有详情 如:id label children
},
renderContent(h, data) {
return (
<div class="treeItem">{data.label}</div>
)
},
}
注意:一定要在style中引入样式文件,否则展开收缩按钮显示不出来
<style lang="less">
@import '../libs/org-tree.less';
</style>
样式文件参考码云
https://gitee.com/hukaicode/vue-org-tree/tree/master/src/styles