本文主要介绍menu组件在有子菜单时如何手动的展开与收起。
展开:
在需要展开的地方先设置openname变量如this.openname = ["设置"];
再在$nextTick中调用updateOpened方法
this.$nextTick(()=> {
this.$refs.child1.updateOpened();
});
收起:
一般是用不着手动收起的,在有多个子菜单并设置了accordion为true时,打开别的子菜单会自动将其他子菜单收起,而我的项目只有一个子菜单,当切换到无子菜单的其他路由时就需要将子菜单收起,这是设置openname变量this.openname = [],再在$nextTick中调用updateOpened方法发现根本不管用,网上搜罗各种资源也只有菜单的手动展开,如此只能自己动脑了,查看了组件源码后发现个opened属性,设置有子菜单的元素的opened为false:this.$refs.child1.$children[2].opened = false;
再在$nextTick中调用updateOpened方法
this.$nextTick(()=> {
this.$refs.child1.updateOpened();
});
完美解决
附上源码
<template> <div class="hello"> <div class="icondiv"></div> <Menu :active-name="selected" @on-select="menuselect" theme="light" ref="child" style="width:200px":open-names="openname" > <template v-for="(item, index) in listdata"> <template v-if="item.child&&item.child.length>0"> <Submenu :name="item.name"> <template slot="title"> <Icon :class="item.icon"></Icon> {{item.name}} </template> <template v-for="sub in item.child"> <MenuItem :name="sub.href">{{sub.name}}</MenuItem> </template> </Submenu> </template> <template v-else> <MenuItem :name="item.href" > <div :class="item.icon"></div> <div class="layout-text">{{item.name}}</div> </MenuItem> </template> </template> </Menu> </div> </template> <script> export default { name: 'menulist', data () { return { listdata:[ { 'name':'公告', 'icon':['ixitong','cipp'], 'href':'#/menu1', }, { 'name':'解惑', 'icon':['ianswer','cipp'], 'href':'#/menu2', }, { 'name':'设置', 'icon':['im-extension','cipp'], 'child':[ { 'name':'审核', 'href':'#/submenu1', }, { 'name':'托管', 'href':'#/submenu2', }, ] } ], selected:"#/submenu1", openname:[], } }, methods: { menuselect (a) { this.$router.push({path:a.split('#')[1]}); }, watchRoute(){ if(this.$refs.child&&this.$route.name!="submenu1"&&this.$route.name!="submenu2"){ this.openname = []; this.$refs.child.$children[2].opened = false; }else{ this.openname = ['设置']; } this.$nextTick(()=> { this.$refs.child.updateOpened(); }); } }, watch:{ $route(){ this.watchRoute(); } }, mounted(){ this.watchRoute(); } } </script>