本文共 6025 字,大约阅读时间需要 20 分钟。
嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如:
/user/foo/profile /user/foo/posts+------------------+ +-----------------+| User | | User || +--------------+ | | +-------------+ || | Profile | | +------------> | | Posts | || | | | | | | || +--------------+ | | +-------------+ |+------------------+ +-----------------+
个人信息
用户列表
import Vue from 'vue' import Router from 'vue-router' import Main from '../views/Main' import Login from '../views/Login' import UserList from '../views/user/List' import UserProfile from '../views/user/proFile' Vue.use(Router); export default new Router({ routes: [ { path: '/login', component: Login }, { path: '/main', component: Main, children: [ { path: '/user/profile', component: UserProfile }, { path: '/user/list', component: UserList } ] } ] })
用户管理 个人信息 用户列表 内容管理 分类管理 内容列表 个人信息 退出登录
说明:
在元素中配置了用于展示嵌套路由,主要使用个人信息展示嵌套路由内容我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 User 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。此时我们就需要传递参数了;
$route方式
{ path: '/main', component: Main, children: [ { path: '/user/profile/:id/:name', name: 'UserProfile', component: UserProfile }, { path: '/user/list', component: UserList } ] }
个人信息
个人信息
{ { $route.params.id}} { { $route.params.name}}
使用 props 的方式
routes: [ { path: '/login', component: Login }, { path: '/main', component: Main, children: [ { path: '/user/profile/:id/:name', name: 'UserProfile', component: UserProfile, props: true }, { path: '/user/list', component: UserList } ] } ]
个人信息
{ { id}} { { name}}
{ path: '/goHome', redirect: '/main' }
回到首页
路由模式有两种
路径带 # 符号,如 http://localhost/#/login
export default new Router({ routes: [] })
路径不带 # 符号,如 http://localhost/login
export default new Router({ mode: 'history', routes: []})
404,你的页面走丢了
import NotFound from '../views/NotFound' export default new Router({ mode: 'history', routes: [ { path: '*', component: NotFound } ] })
路由钩子
export default { name: "UserProFile", props: ['id','name'], beforeRouteEnter: (to,from,next) => { console.log('进入路由之前') next() }, beforeRouteLeave: (to,from,next) => { console.log('进入路由之后') next() } }
参数说明:
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios)
{ "name": "狂神说Java", "url": "https://blog.kuangstudy.com", "page": 1, "isNonProfit": true, "address": { "street": "含光门", "city": "陕西西安", "country": "中国" }, "links": [ { "name": "bilibili", "url": "https://space.bilibili.com/95256449" }, { "name": "Java", "url": "https://blog.kuangstudy.com" }, { "name": "百度", "url": "https://www.baidu.com/" } ] }
export default { name: "UserProFile", props: ['id','name'], beforeRouteEnter: (to,from,next) => { console.log('进入路由之前');//加载数据 next(vm => { vm.getData();//进入路由之前执行getData() }) }, beforeRouteLeave: (to,from,next) => { console.log('进入路由之后'); next() }, methods: { getData() { this.axios({ method: 'get', url: 'http://localhost:8080/static/mock/data.json' }).then((response) => { console.log(response) }) } } }
转载地址:http://tqux.baihongyu.com/