vue - 路由(vue-router)

37 阅读2分钟

1. 路由模式

  • hash模式:url 中 # 以及 # 后面的字符称之为 hash,用 window.location.hash 读取,hash 不被包括在 HTTP 请求中,hash 不会重复加载页面。
  • history模式:采用 H5 新特性,pushState()、replaceState() 可以对浏览器历史记录栈进行修改,及 popState 事件监听到状态变更。

2. 路由传参

export default new Router({
    routes: [
        {
            name: 'A',
            path: '/home/a/:id',
            component: A,
        },
    ],
})
<router-link :to="{path: '/home/a/123', query: { name: 'abc' } }">XXX</router-link>
<!--
    localhost:8080/#/home/a/123?name=abc
-->

获取参数:

let id = this.$route.params.id
let name = this.$route.query.name

3. 路由的钩子函数

  • 全局的路由钩子函数:
    • beforeEach 全局前置守卫
    • afterEach 全局后置守卫
  • 单个的路由钩子函数:beforeEnter
  • 组件内的路由钩子函数:beforeRouteEnter、beforeRouteLeave、beforeRouteUpdate

3.1 beforeEach、afterEach

beforeEach:每次每个路由改变的时候都得执行一遍。

【参数】:to、from、next

  • to:将要进入的目标路由对象,to 对象下面的属性:
    • path、params、query、hash、fullPath、matched、name、meta
  • from:当前导航正要离开的路由
  • next:一定要调用该方法来 resolve 这个钩子
    • 调用:next(参数或空)
import VueRouter from 'vue-router';

const router = new VueRouter({
  routes: [
    // 路由映射
  ],
});

router.beforeEach((to, from, next) => {
  // 做一些逻辑处理,例如
  if(to.meta.requireAuth) {
    if(cookies('token')) {
      next();
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath // 将跳转的路由 path 作为参数,登录成功后跳转到该路由
        },
      })
    }
  } else {
    next();
  }
})

// 路由异常错误处理
router.onError((error) => {
  // do something
})

afterEach:页面加载之后

3.2 beforeEnter 路由独享的守卫

const router = new VueRouter({
  routes: [
    {
      path: '/test',
      component: TextDecoderStream,
      beforeEnter: (to, from, next){
        // do something
      }
    },
  ]
})

3.3 beforeRouteEnter、beforeRouteLeave、beforeRouteUpdate

const Test = {
  template: '',
  beforeRouteEnter(to, from, next){
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不能获取组件实例 this
    // 因为当前钩子执行前,组件实例还没被创建
  },
  beforeRouteUpdate(to, from, next){
    // 在当前路由改变,但是该组件被复用时调用
    // 如:带有动态参数的路径 /test/:id 在 /test/1 和 /test/2 之间跳转的时候
    // 由于会渲染同样的 Test 组件,因此组件实例会被复用,而这个钩子就会被调用
    // 可以访问组件实例 this
  },
  beforeRouteLeave(to, from, next){
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 this
  },
};