主要是利用defaultOpenKeys和selectedKeys两个API
template部分:
<a-menu
theme="dark"
mode="inline"
:defaultOpenKeys="openKeys"
:selectedKeys="selectedKeys"
:style="{ height: '100%', borderRight: 0, minHeight: 'calc(100vh - 64px)' }"
>
<a-sub-menu key="sub1">
<span slot="title"><a-icon type="user" />sub1</span>
<a-menu-item key="/111">
<router-link :to="{name: 'one'}">
111
</router-link>
</a-menu-item>
<a-menu-item key="/222">
<router-link :to="{name: 'two'}" >
222
</router-link>
</a-menu-item>
<a-menu-item key="/333">
<router-link :to="{name: 'three'}" >
333
</router-link>
</a-menu-item>
</a-sub-menu>
<a-sub-menu key="sub2">
<span slot="title"><a-icon type="laptop" />sub2</span>
<a-menu-item key="/444">
<router-link :to="{name: 'four'}" >
444
</router-link>
</a-menu-item>
</a-sub-menu>
<a-sub-menu key="sub3">
<span slot="title"><a-icon type="notification" />sub3</span>
<a-menu-item key="/555">
<router-link :to="{name: 'five'}" >
555
</router-link>
</a-menu-item>
</a-sub-menu>
</a-menu>
在data中定义字段
data () {
return {
openKeys: ['sub1'],
selectedKeys: [this.$route.path.substr(this.$route.path.lastIndexOf('/'))]
}
}
展开方法:
methods: {
fetch () {
var temp
// 针对二级路由页面添加的判断
if (this.$route.path.indexOf('/', 1) === this.$route.path.lastIndexOf('/')) {
temp = this.$route.path.substr(this.$route.path.lastIndexOf('/'))
} else {
temp = this.$route.path.substring(this.$route.path.indexOf('/', 1), this.$route.path.lastIndexOf('/'))
}
this.selectedKeys = [temp]
// 根据不同的菜单项展开SubMenu
if (this.selectedKeys[0] === '/111' || this.selectedKeys[0] === '/222' || this.selectedKeys[0] === '/333') {
this.openKeys = ['sub1']
} else if (this.selectedKeys[0] === '/444') {
this.openKeys = ['sub2']
} else if (this.selectedKeys[0] === '/555') {
this.openKeys = ['sub3']
}
}
}
mounted加载与watch监听
mounted () {
this.fetch()
},
// 加上监听就能解决刷新页面后展开不正确了
watch: {
$route: {
handler: function (val, oldVal) {
console.log(val)
this.fetch() // 展开方法
},
// 深度观察监听
deep: true
}
}