用<router-link>
做导航引发的选中图标不高亮bug;
如图所示:
引发bug的情况:
在子路由中使用<router-link>
组件,在切换<router-view>
时导致选项不高亮。
百思不得其解,百度说是路由配置方法不对,这里给出另外一种经过实践可用的方法。
解决方案:
在父组件中监听子路由变化,动态的给父组件选中的标签加上高亮class。
代码:
template代码
<template>
<div class="container">
<div class="topContainer">
<ul class="task-list">
<router-link v-for="(item, index) in tabs" :to="{name:item.id}">
<div class="itembox" :class="selected==item.id?'activeText':'text'" @click="selected=item.id">
<span>{{item.name}}</span>
</div>
</router-link>
</ul>
</div>
<router-view @selectedFun="selectedFun" class=""></router-view>
</div>
</template>
js代码
<script>
export default {
data() {
return {
selected: 'OrganStructure',
tabs: [{
id: "OrganStructure",
name: "组织架构",
active: false
},{
id: "AuthorityManage",
name: "权限管理",
active: false
},{
id: "CustomProcess",
name: "自定义流程",
active: false
}]
}
},
watch: {
selected: function (val) {// 监听selected值,更新缓存中的值
localStorage.setItem('selectedStorage',val);
}
},
beforeRouteLeave(to, from, next){ // 离开页面时设置为默认路由,很重要
this.selected='OrganStructure'
next();
},
mounted(){
window.addEventListener('beforeunload', e => { // 监听页面刷新,保留当前路由的选中状态
localStorage.setItem('selectedStorage', this.selected);
});
},
created() {
if(localStorage.getItem('selectedStorage')!=null){// 若缓存中没有值就设置为默认的路由
this.selected=localStorage.getItem('selectedStorage');
}else{
this.selected='OrganStructure'//
}
},
methods: {
selectedFun(val){//切换导航时,将selected设为当前项
this.selected=val;
}
}
}
</script>
<style scoped lang='less'>
.page{
height: 90px;
}
.container{
display: flex;
flex-direction: column;
height: 100%;
.topContainer{
display: flex;
align-items: flex-start;
height: 60px;
}
.task-list{
display: flex;
flex-direction: row;
.itembox{
padding:10px 20px;
background: #a6b0c0;
border-radius: 10px;
text-align: center;
color: #fff;
margin: 0 10px;
cursor: pointer;
}
.activeText{
background:linear-gradient(to right, #00f1d9 ,#00a1f3)
}
}
}
.contentBox {
overflow: hidden;
overflow-y: auto;
height: 90%;
}
</style>
bug修复后,得到预期情况:
列出部分路由
{ path: 'CustomProcess', name: 'CustomProcess',
component: CustomProcess,redirect: '/Authorize/CustomProcess/CustomExamine',
children:[
{ path: 'CustomExamine', name: 'CustomExamine', component: CustomExamine },
{ path: 'CustomApprove', name: 'CustomApprove', component: CustomApprove }
]
}
若有错误欢迎指出