使用強大的 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>
|