Vue自定義樹形控制元件使用詳解
阿新 • • 發佈:2021-08-18
本文例項為大家分享了自定義樹形控制元件的使用方法,供大家參考,具體內容如下
效果圖:
資料結構:
tree: { title: '',// 標題(姓名) key: '0',head: '',// 頭像 selectStatus: false,// checkBox選中狀態 children: [ { title: '旺旺一部',key: '0-0',selectStatus: false,children: [ { key: '0-0-0',title: '旺仔1',head: require('@/assets/wan.jpg'),selectStatus: false } ] },{ title: '旺旺二部',key: '0-1',children: [ { title: '旺旺二部一隊',key: '0-1-0',children: [ { title: '旺旺二部一隊一班',key: '0-1-0-2',children: [ { title: '旺仔3',key: '0-1-0-2-0',selectStatus: false } ] } ] } ] } ] },
思路:
/*自定義樹形控制元件的核心就是“元件自己呼叫自己” 這裡將樹形控制元件封裝成一個子元件*/ <template> <div> <div class="tree-custom"> <div :style="indent" @click="toggleChildren"> //toggleChildren事件為“展開內容”、“關閉內容”的控制事件 /* 這裡是遞迴資料顯示的具體內容 例如:本專案遞迴的具體內容從效果圖上看就是“圖片/頭像”、“標題/名字”、“null/CheckBox” 效果圖顯示邏輯是: <div v-if="!headImg && label" > //如果沒有頭像圖片有標題,則顯示 “箭頭-標題”樣式 </div> <div v-if="headImg"> //如果有頭像圖片,則顯示 “頭像-姓名-checkBox”樣式 </div> */ </div> <tree-custom // “自己呼叫自己” :key="children.key" // key值唯一 v-for="children in treeData" v-if="showChildren" // 根據 toggleChildren事件 判斷是否展開內容 :treeData="children.children" // 下面都是一些屬性,應該都能看懂吧!不多說了! :label="children.title" :headImg="children.head" :pkid="children.key" :depth="depth+1" // 這個是用來控制每行縮排的樣式,可移步下方=>indent ()看具體用處 :selectStatus="children.selectStatus" v-bind="$attrs" // 這兩個是用來實現祖孫元件通訊的 v-on="$listeners" > </tree-custom> </div> </div> </template> <script> export default { name: 'TreeCustomwww.cppcns.com',// 要給我們的元件一個名字!不然怎麼呼叫呢 data () { return { showChildren: true,// 這個就是控制是否顯示內容的data~也就是展開和收起! currentInfoData: {} // 這個的用處是獲取當前行的資料,為了簡潔在上方程式碼的具體用處已經被我刪掉了~意義不大 } },//物件的預設值應由一個工廠函式返回,避免採坑 props: { treeData: { type: Array,default: () => [] },label: { type: String,default: () => '' },depth: { type: Number,default: () => 0 },headImg: { type: String,Xuugxpkid: { type: String,selectStatus: { type: Boolean,default: () => null } },computed: { indent () { // 定義不同層級的縮排樣式 return { transform: `translate(${(this.depth - 1) * 15}px)` } } },methods: { toggleChildren () { this.showChildren = !this.showChildren },checkBoxSelectChange (e) { const checked = e.target.checked if (checked) { //使用$listeners方法呼叫祖輩的函式,因為這邊是遞迴元件所以元件之間可能並不是嚴格的父子關係,所以$emit、$parent等方法都是不合適的 this.$listeners.addSelectedData(this.currentInfoData) } if (!checked) { this.$listeners.deleteSelectedData(this.currentInfoData) } },getCurrentInfo (label,headImg,pkid) { this.currentInfoData = { key: pkid,title: label,head: headImg } } } } </script>
/*元件呼叫方法*/ <div class="tree-scroll"> <tree-custom :label="tree.title" :headImg="tree.head" :treeData="tree.children" :pkid="tree.key" :depth="0" :selectStatus="tree.selectStatus" @addSelectedData="addSelectedData" @deleteSelectedData="deleteSelectedData" /> </div>
以上就是本文的全部www.cppcns.com內容,希望對大家的學習有所幫助,也希望大家多多支援我們。