日前,在工作中有一个类似chrome书签管理器的需求,在调研了iview的Tree组件,Vue-dragging,Vue-drag-tree后发现并不能满足需求,故而计划自己实现。
本文着重实现树形结构的展示,拖拽功能的完善后续会完善。
Vue作为组件化的框架,原则上所有的页面元素都由数据来进行驱动,要实现template模板的递归就需要组件递归:
贴出目录结构
数据结构:
[ { title: 'aaa', expand: false, }, { title: 'bbb', expand: false, }, { title: 'ccc', expand: true, children: [ { title: 'parent 1-1', expand: true, children: [ { title: 'leaf 1-1-1', expand: true, children: [ { title: 'leaf 1-1-1', }, { title: 'leaf 1-1-2', }, ], }, { title: 'leaf 1-1-2', }, ], }, { title: 'parent 1-2', expand: true, children: [ { title: 'leaf 1-2-1', }, { title: 'leaf 1-2-1', }, ], }, ], }, ]
tree组件中核心代码:
<template> <div class="tree"> <ul> <li v-for='a in data'> <span v-if="a.children" @click.stop='a.expand=!a.expand' class="tree-icon">点我</span> <myTree :data='a.children' v-if='!a.expand'></myTree> </li> </ul> </div> </template> <script> import Vue from 'vue'; export default { name: 'myTree', data() { return { }; }, props: ['data'], mounted() { }, methods: { }, }; </script>
父组件就很简单的调用传参就好了:
<template> <div class="catalog-tree"> <myTree :data='treeData'></myTree> </div> </template> <script> import myTree from './tree'; export default { name: 'catalogTree', data() { return { treeData: [ { title: 'aaa', expand: false, }, { title: 'bbb', expand: false, }, { title: 'ccc', expand: true, children: [ { title: 'parent 1-1', expand: true, children: [ { title: 'leaf 1-1-1', expand: true, children: [ { title: 'leaf 1-1-1', }, { title: 'leaf 1-1-2', }, ], }, { title: 'leaf 1-1-2', }, ], }, { title: 'parent 1-2', expand: true, children: [ { title: 'leaf 1-2-1', }, { title: 'leaf 1-2-1', }, ], }, ], }, ], }; }, components: { myTree, }, mounted() { }, methods: { }, }; </script>
至此,简单的Vue目录树就完成了,拖拽等功能还在完善中,敬请期待!