vue-利用遞迴元件完成一個樹形元件
阿新 • • 發佈:2020-09-15
這裡寫一個利用利用遞迴元件完成一個樹形元件
這裡利用ul>li的方式進行基礎
tree.vue中,先寫一個基礎結構 當有子選單的時候才顯示 + 表示可點選
<template> <li @click.stop="toggleOpen"> <span >{{ model.title }} <i v-if="model.children.length > 0">[{{ open ? "-" : "+" }}]</i></span > </li> </template>
基礎結構搭好以後,開始準備寫遞迴元件
<template> <li @click.stop="toggleOpen"> <span >{{ model.title }} <i v-if="model.children.length > 0">[{{ open ? "-" : "+" }}]</i></span > //open是 開啟合起的展示圖示 //當存在子選單 才進行渲染 ul,並遞迴元件顯示完全 <ul v-show="open" class="item" v-if="model.children.length > 0"> <item v-for="model in model.children" :key="model.title" :model="model" ></item> </ul> </li> </template>
js:
export default { name: "item", //這裡要和呼叫的名字相同 props: { model: { type: Object, required: true } }, data() { return { open: false }; }, methods: { toggleOpen() { this.open = !this.open; //顯示和隱藏 注意.stop 阻止冒泡 } } };
父元件:
<template> <div> <ul> <item :model="data"></item> </ul> </div> </template> <script> import item from "./tree"; export default { name: "app", data() { return { data: { title: "第0級", children: [ { title: "第一級", children: [ { title: "第一級的第二級1", children: [] }, { title: "第一級的第二級2", children: [] } ] }, { title: "第2級", children: [ { title: "第2級的第二級1", children: [ { title: "第2級的第二級1第三級1", children: [] } ] }, { title: "第2級的第二級2", children: [] } ] }, { title: "第3級", children: [] } ] } }; }, components: { item } }; </script>
這裡的資料結構需要注意一下
這裡用的是遞迴元件,v-for中迴圈的每一項是一個物件,所以元件一開始也需要接受一個物件
效果圖: