父组件 selectTree.vue
<template> <div class="content"> <expenseTypeTree @pickTreeItemFn="pickTreeItemFn" v-for="(item, index) in treeList" :key="index" :name="item.name" :treeItem="item" :depth="0" ></expenseTypeTree> </div> </template> <script> import Tree from "./tree.vue"; export default { name: "selectTree", components: { Tree, }, data() { return { treeList: [ { name: "数据1", hasChild: true, id: 1, children: [ { name: "数据1-1", hasChild: true, id: 2, children: [ { name: "数据1-1-1", hasChild: false, id: 3, }, ], }, { name: "数据1-2", hasChild: false, id: 4, }, ], }, { name: "数据2", hasChild: true, id: 5, children: [ { name: "数据2-1", hasChild: true, id: 6, children: [ { name: "数据2-1-1", hasChild: false, id: 7, }, ], }, { name: "数据2-2", hasChild: false, id: 8, }, ], }, ], }; }, created() {}, methods: { pickTreeItemFn(treeItem) { // 处理选中项 }, }, }; </script>
子组件 tree.vue
<template> <div class="item" @click.stop="toggleChildren()"> <div> <span class="item-info"> <span>{{ treeItem.name }}</span> </span> </div> <!-- 将children传递给组件,实现递归 --> <div v-if="isOpen" class="item-child"> <Tree v-for="(item, index) in treeItem.children" :key="index" :name="item.name" :treeItem="item" @pickTreeItemFn="pickTreeItemFn" ></Tree> </div> </div> </template> <script> export default { name: "Tree", //自己调用自己 props: ["treeItem", "name"], computed: { isFolder() { return this.treeItem.hasChild; }, }, data() { return { isOpen: false, }; }, created() {}, methods: { pickTreeItemFn(treeItem) { this.$emit("pickTreeItemFn", treeItem); }, toggleChildren() { if (this.isFolder) { let that = this; setTimeout(function name(params) { that.isOpen = !that.isOpen; }, 100); } else { // 选中 this.$emit("pickTreeItemFn", this.treeItem); } }, }, }; </script>
问题一、折叠事件需要阻止事件冒泡
@click.stop="toggleChildren()"
问题二、父子组件通信少通信一层
pickTreeItemFn(treeItem) {
this.$emit("pickTreeItemFn", treeItem);
},
参考地址:https://blog.csdn.net/weixin_45325262/article/details/95332234
原文:https://www.cnblogs.com/zhaomeizi/p/14819388.html