vue-router

    科技2022-08-15  119

    vue-router(路由守卫)

    1.分类2.基本用法3.路由导航解析流程4.vue-router的三种模式

    1.分类

    路由守卫为: 全局守卫:beforeEach 后置守卫:afterEach 全局解析守卫:beforeResolve 路由独享守卫:beforeEnter

    组内路由守卫:beforeRouteEnter,beforeRouteUpdate,beforeRouteLeave

    2.基本用法

    beforeEach router.beforeEach((to, from, next) => { // ... })

    to: Route: 即将要进入的目标 路由对象 from: Route: 当前导航正要离开的路由 next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。 next参数 next()//直接进to 所指路由 next(false) //中断当前路由 next(‘route’) //跳转指定路由 next(‘error’) //跳转错误路由 确保要调用 next 方法,否则钩子就不会被 resolved

    beforeResolve router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用

    afterEach

    router.afterEach((to, from) => { // ... }) beforeEnter routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] beforeRouteEnter beforeRouteEnter(to, from, next)=>{ //不能调用this,该路由调用时,组件并未被初始化 } beforeRouteUpdate beforeRouteUpdate(to,from,next){ //路由动态参数改变,组件被复用时调用(/user/1=>1/user/2) //可以调用this } //(2.2 新增) beforeRouteLeave <span style="font-weight:normal;">beforeRouteLeave(to, from, next)=>{ //离开该组件时调用 //可以访问this //通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消 }</span>

    3.路由导航解析流程

    路由导航开始在当前路由调用beforeRouterLeave调用beforeEach在重用组件中调用beforeRouteUpdate调用beforeEnter解析异步路由组件在被激活的路由组件里调用beforeRouteEnter调用beforeResolve导航被确认调用全局的afterEach触发DOM更新用创建好的实例调用beforeRouteEnter中传递给next的函数

    4.vue-router的三种模式

    hash 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载,其显示的网路路径中会有 “#” 号。这是最安全的模式,因为他兼容所有的浏览器和服务器。 http://localhost:8080/#/home history 美化后的hash模式,会去掉路径中的 “#”。依赖于Html5 的history,pushState API,所以要担心IE9以及一下的版本,感觉不用担心。 http://localhost:8080/home abstract 适用于所有JavaScript环境,例如服务器端使用Node.js。如果没有浏览器API,路由器将自动被强制进入此模式。

    设置 三选一

    const router = new VueRouter({routes, mode:'hash|history|abstract',})
    Processed: 0.010, SQL: 8