一个简单的基于vue手写的tree树

时间:2024-11-16 15:14:20
<template> <ul> <li v-for="item in data" :key=""> <p> <span v-if=" && > 0" :class="['icon-triangle', ? 'rotate' : 'rotateFalse']" @click.stop="openShow(item)" ></span> <span @click="treeItemClick(item)">{{ item.name }}</span> </p> <transition name="slide-fade"> <!-- 递归组件循环引用,要有终止条件,再把子级传进去再次遍历--> <myTree v-show=" && && > 0" :data="" @myTreeClick="myTreeClick" ></myTree> </transition> </li> </ul> </template> <script> import myTree from "@/components/"; export default { name: "myTree", comments: { myTree, }, props: { // 树形数据 data: { type: Array(), default: () => [], }, // 是否手风琴 isShouFengQin: { type: Boolean, default: false, }, }, data() { return {}; }, created() { }, methods: { openShow(item) { this.$nextTick(() => { if (this.isShouFengQin) { this.treeDataHandle(this.data); } item.isOpen = !item.isOpen; // 重新开启或者关闭 }); }, // 遍历将tree树全部关闭状态 treeDataHandle(data) { for (let i = 0; i < data.length; i++) { if (data[i].children && data[i].children.length > 0) { this.treeDataHandle(data[i].children); } data[i].isOpen = false; } }, // 点击事件 treeItemClick(data) { this.$emit("myTreeClick", data); }, myTreeClick(data){ this.$emit("myTreeClick", data); } }, }; </script> <style lang="scss" scoped> ul li { margin-left: -10px; } .icon-triangle { display: inline-block; border: 7px solid transparent; border-bottom-color: #ccc; transform: rotate(90deg); :hover { cursor: pointer; } } li { margin-left: 22px; margin-top: 13px; :hover { cursor: pointer; } } .rotate { transform: rotate(180deg); transition: all 1s; position: relative; top: 5px; right: 5px; } .rotateFalse { transform: rotate(90deg); transition: all 0.2s; } .slide-fade-enter-active { transition: all 0.3s ease; } .slide-fade-leave-active { transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1); } .slide-fade-enter, .slide-fade-leave-to { transform: translateX(10px); opacity: 0; } </style>