当前位置: 首页 > Web前端 > JavaScript

Vue实现无限树选择器(无第三方依赖)

时间:2023-03-27 11:24:23 JavaScript

......somecode......在Vue中实现这样的无限树选择器并不难。关键点是使用递归组件和高级事件监控。下面一步一步来吧。简单实现如下样式创建一个Tree.vue组件(为了阅读方便,代码省略):......somecode......expandandcontract我们用CSS来创建一个三角形:.triangle{宽度:0;高度:0;边框:6px实心透明;左边框:8px纯灰色;过渡:全部0.1s;左:6px;margin:6px000;}然后在展开的时候定义一个类,通过旋转角度调整定位:.caret-down{transform:rotate(90deg);左:2px;margin:9px000;}由于控制每个节点展开和关闭的变量是独立的,为了不污染数据,这里定义一个对象tapScopes来控制。记得使用$set让视图响应变化://当三角形被点击时,图标变化:changeStatus(index){this.$set(this.tapScopes,index,this.tapScopes[index]?(this.tapScopes[index]==='open'?'close':'open'):'open')}递归渲染现在我们只渲染第一层数据,如何循环渲染下一层至于data,其实很简单,只要在上面的TODO位置插入组件本身即可(相当于把自己介绍成组件),只要组件设置了name属性,Vue就可以调用组件://....一些代码....constCARETS={open:'caret-down',close:'caret-right'}exportdefault{name:'TreeMenus',props:{data:{type:Array,默认:()=>[],},isSelect:{type:Boolean,default:false,},props:{type:Object,default:()=>{return{children:'children',label:'title',key:'id',}},},},data(){return{car??ets:CARETS,tapScopes:{},scopes:{},}},methods:{operation(type,treeNode){this.$emit('operation',{type,treeNode})},tap(item,index){this.$emit('node-click',item)},changeStatus(index){this.$emit('change',this.data[index])//图形化this.$set(this.tapScopes,index,this.tapScopes[index]?(this.tapScopes[index]==='open'?'close':'open'):'open')//展开关闭合this.$set(this.scopes,index,this.scopes[索引]?false:true)},asyncchecked(item){this.$emit('checked',item)},},}.treeMenu{padding-left:20px;复制代码列表样式:无;位置:相对;user-select:none;}.triangle{transition:all0.1s;左:6px;边距:6px000;位置:绝对;游标:指针;宽度:0;高度:0;边框:6px实心透明;border-left:8pxsolidgrey;}.caret-down{transform:rotate(90deg);左:2px;边距:9px000;}.checkbox-wrap{显示:flex;align-items:center;}.checkbox{margin-right:0.5rem;}.treeNode:hover,.treeNode:hover>.operation{color:#3771e5;background:#f0f7ff;}.treeNode--select{background:#f0f7ff;}.treeNode:hover>.operation{opacity:1;}p{position:relative;显示:弹性;align-items:center;}p>.title{cursor:pointer;}a{color:cornflowerblue;}.operation{position:absolute;右:0;字体大小:18px;不透明度:0;}Mock.jsexportdefault{stat:1,msg:'ok',data:{list:[{key:1,title:'一级机构',children:[{key:90001,title:'检测机构111',children:[{key:90019,title:'检测机构111-2',},{key:90025,title:'机构机构',children:[{key:90026,title:'机构agency-2',},],},],},{key:90037,title:'另一个机关部门',},],},{key:2,title:'小卖部主舵',children:[{key:90037,title:'小卖部河滨分局',},],},],},}调用组件: