在本篇文章當中,將采用vue+iview的tree組件實現樹型結構。
實現效果圖
要實現這種自定義效果其實不難,而且官網有相應的實例代碼,如下所示:
<template>
<Tree :data="data5" :render="renderContent"></Tree>
</template>
<script>
export default {
data () {
return {
data5: [
{
title: 'parent 1',
expand: true,
render: (h, { root, node, data }) => {
return h('span', {
style: {
display: 'inline-block',
width: '100%'
}
}, [
h('span', [
h('Icon', {
props: {
type: 'ios-folder-outline'
},
style: {
marginRight: '8px'
}
}),
h('span', data.title)
]),
h('span', {
style: {
display: 'inline-block',
float: 'right',
marginRight: '32px'
}
}, [
h('Button', {
props: Object.assign({}, this.buttonProps, {
icon: 'ios-add',
type: 'primary'
}),
style: {
width: '64px'
},
on: {
click: () => { this.append(data) }
}
})
])
]);
},
children: [
{
title: 'child 1-1',
expand: true,
children: [
{
title: 'leaf 1-1-1',
expand: true
},
{
title: 'leaf 1-1-2',
expand: true
}
]
},
{
title: 'child 1-2',
expand: true,
children: [
{
title: 'leaf 1-2-1',
expand: true
},
{
title: 'leaf 1-2-1',
expand: true
}
]
}
]
}
],
buttonProps: {
type: 'default',
size: 'small',
}
}
},
methods: {
renderContent (h, { root, node, data }) {
return h('span', {
style: {
display: 'inline-block',
width: '100%'
}
}, [
h('span', [
h('Icon', {
props: {
type: 'ios-paper-outline'
},
style: {
marginRight: '8px'
}
}),
h('span', data.title)
]),
h('span', {
style: {
display: 'inline-block',
float: 'right',
marginRight: '32px'
}
}, [
h('Button', {
props: Object.assign({}, this.buttonProps, {
icon: 'ios-add'
}),
style: {
marginRight: '8px'
},
on: {
click: () => { this.append(data) }
}
}),
h('Button', {
props: Object.assign({}, this.buttonProps, {
icon: 'ios-remove'
}),
on: {
click: () => { this.remove(root, node, data) }
}
})
])
]);
},
append (data) {
const children = data.children || [];
children.push({
title: 'appended node',
expand: true
});
this.$set(data, 'children', children);
},
remove (root, node, data) {
const parentKey = root.find(el => el === node).parent;
const parent = root.find(el => el.nodeKey === parentKey).node;
const index = parent.children.indexOf(data);
parent.children.splice(index, 1);
}
}
}
</script>
可以從官網的示例代碼中發現,如果要自定義樹型控件內容的話,需要采用render函數,該Render函數的第二個參數包含三個字段,分別為根節點、當前節點、當前節點的數據。
在data數據里面的render設置的自定義根節點,而通過bind綁定的render則是用來自定義子節點的,而文章開頭展示的效果圖當中,要實現的效果根節點和子節點的樣式是一樣的,所以在這可以共用一個render函數。
//公共的render函數
renderContent (h, { root, node, data }) {
return h('span', {
style: {
display: 'inline-block',
width: '100%'
}
}, [
h('span', [
h('img', {
attrs:{
src:data.src //圖片的地址
},
style: {
verticalAlign: "middle",
display:"inline-block",
margin:'0px 5px'
}
}),
h('span', data.subprojectName) //subprojectName屬性存放的是需要顯示的文本信息
])
]);
}
從代碼中可以看出,這個公共的render也就是實現了圖片后面跟上文本信息,圖片的src存放在數據當中的src屬性中,文本信息存放在subprojectName屬性中。
在iview的官方示例當中,還存在著可以勾選多選以及子菜單延遲加載的功能,延遲加載也就是去請求API將數據返回了,具體的都可以直接參考官方示例。