想要在 Vue 中實現一個這樣的無限級樹形選擇器其實並不難,關鍵點在於利用
遞迴元件
和
高階事件監聽
,下面我們就一步步來實現它。
簡單實現下樣式
建立
Tree。vue
元件(為方便閱讀,程式碼有省略):
{{ item。title }}
展開收縮我們使用 CSS 來建立一個三角形:
。triangle { width: 0; height: 0; border: 6px solid transparent; border-left: 8px solid grey; transition: all 0。1s; left: 6px; margin: 6px 0 0 0;}
然後定義一個展開時的
class
,旋轉角度調整一下定位:
。caret-down { transform: rotate(90deg); left: 2px; margin: 9px 0 0 0;}
由於每個節點控制展開閉合的變數都是獨立的,為了不汙染資料,這裡我們定義一個物件
tapScopes
來控制就好,記得使用
$set
來讓檢視響應變化:
// 當點選三角形時,圖示變化:changeStatus(index) { this。$set(this。tapScopes, index, this。tapScopes[index] ? (this。tapScopes[index] === ‘open’ ? ‘close’ : ‘open’) : ‘open’)}
遞迴渲染
現在我們只渲染了第一層資料,如何迴圈渲染下一級資料呢,其實很簡單,往上面
TODO
的位置插入元件自身即可(相當於引入了自身作為
components
),只要元件設定了
name
屬性,
Vue
就可以呼叫該元件,:
Mock.js
export default { stat: 1, msg: ‘ok’, data: { list: [ { key: 1, title: ‘一級機構部門’, children: [ { key: 90001, title: ‘測試機構111’, children: [ { key: 90019, title: ‘測試機構111-2’, }, { key: 90025, title: ‘機構機構’, children: [ { key: 90026, title: ‘機構機構-2’, }, ], }, ], }, { key: 90037, title: ‘另一個機構部門’, }, ], }, { key: 2, title: ‘小賣部總舵’, children: [ { key: 90037, title: ‘小賣部河邊分部’, }, ], }, ], },}
呼叫元件
:
以上就是文章的全部內容,希望對你有所幫助!如果覺得文章寫的不錯,可以點贊收藏,也歡迎關注,我會持續更新更多前端有用的知識與實用技巧,我是茶無味de一天,希望與你共同成長~