vue-cli 默认路由再子路由选中下的选中状态问题

因项目需求,需要在默认路由下面的两个子路由进行切换,当开始以为不就是路由切换?so easy!想象很丰满,现实很骨感!那就看一下遇到的问题吧!

{path: '/',component: resolve => require(['@/components/LiveList'],resolve),
    	children:[
        {
    		path:'',
    		name:'livelist',
    		meta:{title:'',index:0},
    		component: resolve => require(['@/components/compts/livelistcom'],resolve)
    	},{
    		path:'livenew',
    		name:'livenew',
    		meta:{title:'',index:1},
    		component: resolve => require(['@/components/compts/livelistnew'],resolve)
    	}]
 },
{
    path:'/user',
    name:'user',
    meta:{title:'用户',index:4},
    component: resolve => require(['@/components/user'],resolve)
},
复制代码

这路由一看没问题吧!

<router-link to="/"><p>首页</p></router-link>//这是底部的切换路由
//下面两个便是首页下面的两个子路由的跳转了
<li><router-link to="/">热门</router-link></li>
<li><router-link to="/livenew">最新</router-link></li>复制代码

看到上面的代码是不是没有发现错误?其实也的确可以运行!而且两个子路由切换关于首页的状态也是没有问题的!

但是当我切换user路由的时候发现,首页路由的状态依旧是选中状态,这个让我很纳闷,按理说user路由跟首页的路由是同级,不出出现这样的问题。既然出现了,为了工作,只能迎难而上,去解决这个问题。

在经过我仔细的查找文档,终于想到了一种解决方案:在官方文档里面有一个redirect(重定向)router.vuejs.org/zh/guide/es…点击链接可以查看官方文档

既然可以重定向那我就试一下这种来解决(毕竟上面的代码和逻辑事再想不出是什么地方出的错误,还望大神指点一二!!!)

废话不多说,直接先解决后的代码:

    {path:'',redirect: '/index'},
    {path: '/index',component: resolve => require(['@/components/LiveList'],resolve),
    	children:[
        {path:'',redirect:'livelist'},
        {
    		path:'livelist',
    		name:'livelist',
    		meta:{title:'',index:0},
    		component: resolve => require(['@/components/compts/livelistcom'],resolve)
    	},{
    		path:'livenew',
    		name:'livenew',
    		meta:{title:'',index:1},
    		component: resolve => require(['@/components/compts/livelistnew'],resolve)
    	}]
    },
    {
        path:'/user',
        name:'user',
        meta:{title:'用户',index:4},
        component: resolve => require(['@/components/user'],resolve)
    }复制代码

而关于路由的跳转也有一些小变化:

<router-link to="/index"><p>首页</p></router-link>//这里依旧是底部导航
//这里便是首页的两个子路由的跳转按钮了
<li><router-link to="/index/livelist">热门</router-link></li>
<li><router-link to="/index/livenew">最新</router-link></li>
复制代码

构思:用重定向,规定默认路由跳转到上面 /index 下面默认的子路由,再由默认的子路由去定向到子路由的 livelist 。(这是在解决问题的时候发现,非默认路由下,子路由切换不会造成默认路由选中不取消的问题,而默认路由一直会存在一个router-link-active的类名,我的选中样式也是基于它的

关于选中时自定义自己的样式可以操作.router-link-active 这个类,而默认路由一直存在这个类,如果没有子路由,或者子路由选中不需要显示父路由也为选中状态的情况下,你可以操作.router-link-exact-active这个类来写自己的选中样式。


转载于:https://juejin.im/post/5b8fb26af265da0ada521b53

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值