vue-router(二)后代路由

时间:2021-04-26 12:22:16
vue-router(二)后代路由
vue-router(二)后代路由

 

关键字:router,children ,router-link,router-view,router-link-active
先理解什么是children?
后代路由为某路由中用到router-view时,会默认加载的路由中的后代路由。
eg:
这里通过点击切换tab实现动态切换路由
先看目录结构:
vue-router(二)后代路由

 

vue-router(二)后代路由
aslide组件:
<div>
    <ul class="tabBar">
        <li v-for="(item,index) in tabList" :key="index"> <router-link :to="{path:item.url}">{{item.tit}}</router-link> </li>
    </ul>
    <router-view class="cont"></router-view>
</div>
样式:
.tabBar { 
    width: 100%; 
    height: 90px; 
    display: flex;
    border-bottom: 1px solid #ccc; 
} 
.tabBar li { 
    display: flex;
    flex: 1; 
    height: 90px; 
} 
.tabBar li a {
    width: 100%; 
    line-height: 90px;
    display: block; 
    text-align: center; 
} 
.router-link-active { 
    color: red; /*background-color: #003399;*/
    border-bottom: 1px solid red; 
} 
.cont { 
    display: flex; 
    justify-content: center; 
    align-items: center; }

 

js:
export default { 
    data() { 
        return { 
            isShow: true,
            tabList: [ 
                { url: '/a', tit: "One" }, 
                { url: '/b', tit: "Two" }, 
                { url: '/c', tit: "Three" } 
            ] 
        } 
    } 
}

 

下来我们还需要对router.js路由模块进行 配置
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router);
Router.prototype.animate = 0;
const _import = file => () => import('@/views/' + file + '.vue');
const _import_ = file => () => import('@/components/' + file + '.vue');
/*
* slide:页面切换动画
* login:是否需要登陆
* */
Vue.use(Router);
 
export  default new Router({
linkActiveClass: "router-link-active",//后代路由被激活时,给路由标签添加指定样式
routes: [
    {
        path: '/',
        name: '首页',
        component: _import('home/index'),
        children: [
        {
            path: '',
            redirect: '/a'
        },//访问首页的时候默认访问后代路由中的a
        {
            path: '/a',
            component: _import_('common/a')
        },
        {
            path: '/b',
            component: _import_('common/b')
        },
        {
            path: '/c',
            component: _import_('common/c')
        }]
    },
    {
        path: "/list",
        name: "list",
        component: _import("home/list"),
        meta: {
            slide: 1,
            login: true
        }
    },
    {
        path: "/search",
        name: "search",
        component: _import("search/index"),
        meta: {
            slide: 1
        }
    },
    {
        path: "/center",
        name: "center",
        component: _import("center/index"),
        meta: {
            slide: 1
        }
    },]
})
主要核心部分如上,我们需要注意的这个属性 linkActiveClass这个属性指定了后代路由被激活时所添加的样式。
实现的思路为:当点击上述router-link中的路由时,实现动态改变router-view中的后代路由以此实现tab的切换。而后代路由中的第一项:redirect:/a意思是默认访问首页的时候,后代路由默认显示哪个