DIV CSS 佈局教程網

Vue.js 元件 treeview:用 ul/li 實作省、市、區多層級聯動
編輯:關於JavaScript     

上一篇寫了兩層的 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 前端組件學習教程》,歡迎延伸閱讀。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved