您好,登錄后才能下訂單哦!
這篇文章給大家介紹Vue2中怎么實現一個無限級分類,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue 樹</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> <style type="text/css"> a{color: #333; text-decoration: none;} ul{padding-left: 15px;} </style> </head> <body> <div id="app"> {{items}} <treelist v-for="(val, index) in items" :item="val" @remove="delItem(index)"></treelist> </div> <template id="treelist-template"> <ul> <div > <a v-if="isFolder" @click="toggle()">[{{open ? '-' : '+'}}]</a> <a v-else >[+]</a> <input type="number" v-model="item.sort"> <input type="text" size="30" v-model="item.name" placeholder="崗位名稱"> <button type="button" @click="addChild()">添加</button> <button type="button" @click="$emit('remove')" v-if="!isFolder">刪除</button> </div> <ul v-show="open" v-if="isFolder"> <treelist v-for="(val, index) in item.children" :item="val" @remove="delItem(index)"></treelist> </ul> </ul> </template> <script> window.onload = function(){ //treelist組件 Vue.component('treelist', { template: '#treelist-template', props: { item: Object }, data: function() { return { open: false } }, computed: { isFolder: function() { return this.item.children && this.item.children.length } }, methods: { toggle: function() { if (this.isFolder) { this.open = !this.open } }, addChild: function() { /*添加內容但不同步到服務器*/ if (!this.isFolder) { Vue.set(this.item, 'children', []) } this.open = true this.item.children.push({ sort: 0, name: '', status: 1, parent_id: this.item['id'] }) }, delItem: function(index){ this.item['children'].splice(index, 1) } } }) new Vue({ el: '#app', data:{ mydata: {}, items: [ {"id":"10","parent_id":"0","sort":"0","name":"其它","status":"0"}, {"id":"12","parent_id":"0","sort":"0","name":"測試","status":"0"}, {"id":"1","parent_id":"0","sort":"0","name":"水果","status":"0", "children":[ {"id":"4","parent_id":"1","sort":"0","name":"香蕉","status":"0"} ] }, {"id":"2","parent_id":"0","sort":"0","name":"飲料","status":"0", "children":[ {"id":"5","parent_id":"2","sort":"0","name":"可樂","status":"0"}, {"id":"6","parent_id":"2","sort":"0","name":"酒水","status":"0", "children":[ {"id":"7","parent_id":"6","sort":"0","name":"啤酒","status":"0"} ] } ] }, {"id":"3","parent_id":"0","sort":"0","name":"美食","status":"0", "children":[ {"id":"8","parent_id":"3","sort":"0","name":"紅燒魚","status":"0"} ] } ] }, methods: { add:function(){ this.mydata['id'] = 100;//從服務器返回的ID號 this.mydata['status'] = 0; this.mydata['parent_id'] = 0; this.items.push(this.mydata); this.mydata = {}; }, delItem: function(index){ this.items.splice(index, 1) } } }); } </script> </body> </html>
關于Vue2中怎么實現一個無限級分類就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。