使用强大的 Render 函数可以自定义节点显示内容和交互,比如添加图标,按钮等。
Render 函数的第二个参数,包含三个字段:
- root <Array>:树的根节点
- node <Object>:当前节点
- data <Object>:当前节点的数据
通过合理地使用 root、node 和 data 可以实现各种效果,其中,iView 给每个节点都设置了一个 nodeKey 字段,用来标识节点的 id。
Render 函数分两种,一种是给当前树的每个节点都设置同样的渲染内容,此 render 通过 Tree 组件的属性 render 传递;另一种是单独给某个节点设置,在该节点的 render 字段内设置;同时设置时,会优先使用当前节点的 Render 函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
<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>
|