本文共 1846 字,大约阅读时间需要 6 分钟。
上一篇介绍了vue-router的配置和简单使用这一篇介绍嵌套路由的实现本篇实例基于上一篇的代码,注释部分将移除于本篇无关的注释,如有疑问请参看之前文章上文说,添加一个路由组件分3步1,定义路由组件2,在router中注册路由3,使用路由:在调用组件中写跳转和显示 下面就按照这三步,添加嵌套路由
嵌套路由也称作子路由,是在上一级下的子级路由,形成嵌套关系在上一篇代码的基础上,在商品页面添加两个子路由,这两个子路由从属于商品页面,分别为新闻和商品列表
为了便于理解,先贴出效果图:
可以看到两个子路由分别为:http://localhost:8080/#/product/newshttp://localhost:8080/#/product/productList
News.vue
- { { news}}
ProductList.vue
- 书名:{ { product.name}}
这两个组件都非常简单,就不做赘述了ProductList商品列表组件,使用了定时器模拟异步请求返回数据
src/router/index.js
/* * 路由器对象模块 */import Vue from 'vue'import VueRouter from 'vue-router'import Product from '../pages/Product.vue'import Home from '../pages/Home.vue'// 引入路由组件import News from '../pages/News.vue'import ProductList from '../pages/ProductList.vue'Vue.use(VueRouter)export default new VueRouter ({ routes: [ { path: '/home', component: Home }, { path: '/product', component: Product, // 嵌套路由 children: [ { // 写法一:全路径 path: '/product/news', component: News }, { // 写法二:继承式 path: 'productList', // 简写,同/product/productList component: ProductList, }, { // 默认重定向 path: '', redirect: '/product/news' } ] }, { path: '/', redirect: '/home' } ]})
路由配置中提供了children来定义嵌套路由,嵌套路由中的路由对象和外层一直子路由的路径有两种方式:全路径和继承式,同时也支持重定向
在调用组件中写跳转和显示 新增的路由组件所属于商品路由组件,所以修改商品路由组件,添加对应的跳转和显示
商品页面
嵌套路由的是不是非常简单,下一篇介绍路由组件的缓存