Vue实现无限级树形选择器(无第三方依赖)
想要在Vue中实现一个这样的无限级树形选择器其实并不难,关键点在于利用递归组件和高阶事件监听,下面我们就一步步来实现它。简单实现下样式
创建Tree。vue组件(为方便阅读,代码有省略):templateulclasstreeMenulivfor(item,index)indata:keyindexivshowitem。children:classtrianglep:classtreeNodelabelclasscheckboxwrapclickchecked(item)inputvifisSelectvmodelitem。checkedtypecheckboxclasscheckboxlabelspanclasstitleclicktap(item,index){{item。title}}span!TODOliultemplatestylescoped。。。。。。somecode。。。。。。style
展开收缩我们使用CSS来创建一个三角形:。triangle{width:0;height:0;border:6pxsolidtransparent;borderleft:8pxsolidgrey;transition:all0。1s;left:6px;margin:6px000;}
然后定义一个展开时的class,旋转角度调整一下定位:。caretdown{transform:rotate(90deg);left:2px;margin:9px000;}
由于每个节点控制展开闭合的变量都是独立的,为了不污染数据,这里我们定义一个对象tapScopes来控制就好,记得使用set来让视图响应变化:当点击三角形时,图标变化:changeStatus(index){this。set(this。tapScopes,index,this。tapScopes〔index〕?(this。tapScopes〔index〕open?close:open):open)}递归渲染
现在我们只渲染了第一层数据,如何循环渲染下一级数据呢,其实很简单,往上面TODO的位置插入组件自身即可(相当于引入了自身作为components),只要组件设置了name属性,Vue就可以调用该组件,:livfor(item,index)indata。。。。somecode。。。。treemenus:dataitem。childrenvbindpropslistylescoped。treeMenu{paddingleft:20px;liststyle:none;position:relative;userselect:none;}。triangle{transition:all0。1s;left:6px;margin:6px000;position:absolute;cursor:pointer;width:0;height:0;border:6pxsolidtransparent;borderleft:8pxsolidgrey;}。caretdown{transform:rotate(90deg);left:2px;margin:9px000;}。checkboxwrap{display:flex;alignitems:center;}。checkbox{marginright:0。5rem;}。treeNode:hover,。treeNode:hover。operation{color:3771e5;background:f0f7ff;}。treeNodeselect{background:f0f7ff;}。treeNode:hover。operation{opacity:1;}p{position:relative;display:flex;alignitems:center;}p。title{cursor:pointer;}a{color:cornflowerblue;}。operation{position:absolute;right:0;fontsize:18px;opacity:0;}style
Mock。jsexportdefault{stat:1,msg:ok,data:{list:〔{key:1,title:一级机构部门,children:〔{key:90001,title:测试机构111,children:〔{key:90019,title:测试机构1112,},{key:90025,title:机构机构,children:〔{key:90026,title:机构机构2,},〕,},〕,},{key:90037,title:另一个机构部门,},〕,},{key:2,title:小卖部总舵,children:〔{key:90037,title:小卖部河边分部,},〕,},〕,},}
调用组件:templateTree:isSelectisSelect:datatreeDatanodeclickhandlechangeloadDatatemplate
以上就是文章的全部内容,希望对你有所帮助!如果觉得文章写的不错,可以点赞收藏,也欢迎关注,我会持续更新更多前端有用的知识与实用技巧,我是茶无味de一天,希望与你共同成长