cli 默认路由再子路由选中下的选中状态问题及解

vue-cli是Vue.js官方脚手架命令行工具,我们可以用它快速搭建Vue.js项目,vue-cli最主要的功能就是初始化项目,既可以使用官方模板,也可以使用自定义模板生成项目,而且从2.8.0版本开始,vue-cli新增了build命令,能让你零配置启动一个Vue.js应用。

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

{path: 'https://www.jb51.net/',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="https://www.jb51.net/"><p>首页</p></router-link>//这是底部的切换路由 //下面两个便是首页下面的两个子路由的跳转了 <li><router-link to="https://www.jb51.net/">热门</router-link></li> <li><router-link to="/livenew">最新</router-link></li>

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

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

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

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

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

{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这个类来写自己的选中样式。

总结

以上所述是小编给大家介绍的vue-cli 默认路由再子路由选中下的选中状态问题及解决代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/b28864849b312ed38d1cdccbfefa31fa.html