vue 设置默认选中路由

需求分析:

  一个导航组件,需要其中一个是选中状态,并且样式呈现高亮,选中的导航对应的页面也需要展示出来。

功能实现:

router-link内置有一个选中状态,当处于当前路由时,会给 router-link 标签加一个类名 router-active-class;

同时还提供有一个 exact 属性,当加了 exact 属性的时候表示精确匹配,也就是会精确匹配 Url,所以如果给主路由设置了 exact 属性的话,当处于子路由时,Url 就匹配不到主路由了,那么主路由也就不会处于选中状态;

所以如果想主路由和子路由都处于选中时不用设置 exact 属性。

标签: router-link //在页面中会解析为我们熟系的 a 标签

类:router-active-class //在这个类名下设置路由选中的高亮样式

属性:exact //精准匹配路由

路由:

routes: [
    {
      path: '/page1',
      name: 'Page1',
      component: Page1
    } ,
    {
      path: '/page2',
      name: 'Page2',
      component: Page2,
      children:[
                {
                   path: '/chil1',
                   name: 'Chil1',
                   component: Chil1
                },
                {
                    path: '/chil2',
                    name: 'Chil2',
                    component: Chil2
                }
            ]     
    },
    {
      path: '/page3',
      name: 'Page3',
      component: Page3
    }
  ]        

html:

<router-link to="/父路由的地址名字/要去的子路由的名字"></router-link>

css:

.router-active-class{
    color: #fff,
    background-color: red    
}