上一篇寫了兩層的 tree,這次進一步用 <ul> 與 <li> 標籤,做出一個可以任意嵌套的省市多級聯動選單。核心只有一個元件,靠 children 欄位遞迴自己。
只要每個節點都有 text,有下層就掛 children 陣列,層數不限。
<template>
<div>
<treeview :model='treedata'></treeview>
</div>
</template>
<script>
import treeview from './TreeView.vue'
export default {
components: { treeview },
data() {
return {
treedata: {
text: '地域',
children: [
{
text: '中國',
children: [
{
text: '陝西省',
children: [
{
text: '西安市',
children: [
{ text: '碑林區' },
{ text: '雁塔區' },
{ text: '未央區' },
{ text: '新城區' }
]
},
{ text: '安康市' },
{
text: '鹹陽市',
children: [{ text: '秦都區' }, { text: '渭城區' }]
},
{ text: '渭南市' }
]
},
{
text: '四川省',
children: [
{ text: '成都市' },
{ text: '綿陽市' },
{ text: '廣元市' }
]
},
{ text: '安徽省' }
]
},
{ text: '俄羅斯' }
]
}
}
}
}
</script><style scoped>
ul, li { list-style-type: none; }
</style>
<template>
<li>
<div @click='toggle'>
<span v-if='hasLeaves'>[{{ open ? '-' : '+' }}]</span>{{ model.text }}
</div>
<ul>
<treeview v-for='child in model.children' :model='child' v-show='open'></treeview>
</ul>
</li>
</template>
<script>
export default {
name: 'treeview',
props: {
model: { type: Object }
},
data() {
return { open: false }
},
computed: {
// 有子節點才顯示 +/- 符號
hasLeaves: function () {
return this.model.children && this.model.children.length
}
},
methods: {
toggle: function () {
this.open = !this.open
}
}
}
</script>1. 元件在模板中直接引用自己的名字(treeview),就形成遞迴渲染,層數由資料決定,不需要寫死。
2. v-for 建議改用 child 之類的名稱,避免迴圈變數與 prop 名稱 model 撞名造成遮蔽。
3. hasLeaves 用 computed 判斷有沒有下一層,葉節點就不顯示展開符號。
4. 展開狀態 open 存在每個節點自己的元件實例裡,因此各層各自獨立開合,互不干擾。
效果圖:

本文已整理進《Vue.js 前端組件學習教程》,歡迎延伸閱讀。