vue-router 基本使用
1. 路由的基本配置

const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }. { path: '/', redirect: '/index' } ]
2. 路由的跳转 命令式导航router-link 与 编程式导航$router.push 导航,name 与 params 搭配,path 与 query 搭配

1. 命令式导航 <router-link to="{name:Home}" /> 2. 编程式导航 <button @click="toHome" /> methods(){ toHome(){ this.$router.push({ name:Home, query:{name:'jack'}, params:{id:3} }) } } // 字符串 router.push('home') // 对象 router.push({ path: 'home' }) // 命名的路由 router.push({ name: 'user', params: { userId: '123' }}) // 带查询参数,变成 /register?plan=private router.push({ path: 'register', query: { plan: 'private' }})
3. 动态路由

{ path: '/home/:id', name: 'Home', component: () => import('../views/home') }, 然后通过 this.$route.params.id 获取 id 值
4. 嵌套路由

{ path: '/home/:id', name: 'Home', component: () => import('../views/home'), children: [ { path: '/child', name: 'Child', component: () => import('../views/child') } ] },
5. 导航守卫

全局守卫 1. 全局前置守卫 router.beforeEach((to, from, next) => { // ... }) 2. 全局解析守卫 router.beforeResolve((to, from, next) => { // ... }) 这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。 3. 全局后置钩子 router.afterEach((to, from) => { // ... }) 路由独享的守卫 const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] }) 组件内的守卫 1. beforeRouteEnter 2. beforeRouteUpdate (2.2 新增) 3. beforeRouteLeave const Foo = { template: `...`, beforeRouteEnter (to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为当守卫执行前,组件实例还没被创建 }, beforeRouteUpdate (to, from, next) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` } }