3.4.嵌套路由
实际生活中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如:
再来看看下面这种更直观的嵌套图:
接下来我们需要实现下面这种效果
核心代码:
1.需要在vip组件中增加嵌套代码
我是vip会员页面
2.在路由配置文件中,需要为vip配置children字段
import Vue from 'vue'
import VueRouter from 'vue-router'
import Course from '@/components/Course'
import Vip from '@/components/Vip'
import Questions from '@/components/Questions'
import Home from '@/components/Home'
import One from '@/components/One'
import Two from '@/components/Two'
import Three from '@/components/Three'
Vue.use(VueRouter)
const router = new VueRouter({
linkActiveClass: 'nav-active',
routes: [
{
path: '/',
component: Home
},
{
path: '/questions',
component: Questions
},
{
path: '/vip',
component: Vip,
children: [
{
path: 'one',
component: One
},
{
path: 'two',
component: Two
},
{
path: 'three',
component: Three
}
]
},
{
path: '/course',
component: Course
}
]
})
export default router
3.5.命名路由和命名视图
3.5.1.命名路由
有时候,通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候,通俗的说,命名路由就是用name属性给路由取一个名字 例如:
1.给'/questions'取一个名字 'wenda'
const router = new VueRouter({
linkActiveClass: 'nav-active',
routes: [
{
path: '/',
component: Home
},
{
path: '/questions',
name: 'wenda', //注意这里的name值 wenda
component: Questions
},
{
path: '/vip',
component: Vip,
children: [
{
path: 'one',
component: One
},
{
path: 'two',
component: Two
},
{
path: 'three',
component: Three
}
]
},
{
path: '/course',
component: Course
}
]
})
2.使用这个name属性
3.5.2.命名视图
有时候想同时 (同级) 展示多个视图,而不是嵌套展示,这个时候可以给视图命名,就可以在一个路由中展示多个视图(组件)
例如: 在home路由中增加侧边栏和主体内容两个组件
核心代码
1.设置路由对应的组件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Course from '@/components/Course'
import Vip from '@/components/Vip'
import Questions from '@/components/Questions'
import Home from '@/components/Home'
import One from '@/components/One'
import Two from '@/components/Two'
import Three from '@/components/Three'
import Sider from '@/components/Sider'
import HomeContent from '@/components/HomeContent'
Vue.use(VueRouter)
const router = new VueRouter({
linkActiveClass: 'nav-active',
routes: [
{
path: '/',
components: { //注意这里的components, default设置的组件 被渲染到 放置的位置
default: Home,
sider: Sider, //Sider组件被渲染到 放置的位置
homecontent: HomeContent //同理
}
},
{
path: '/questions',
name: 'wenda',
component: Questions
},
{
path: '/vip',
component: Vip,
children: [
{
path: 'one',
component: One
},
{
path: 'two',
component: Two
},
{
path: 'three',
component: Three
}
]
},
{
path: '/course',
component: Course
}
]
})
export default router
2.渲染视图
螺钉课堂视频课程地址:http://edu.nodeing.com