doina

一个小菜鸟运维工程师.

vue-route 导航守卫和keep-alive

[toc]

vue-route 导航守卫

  • https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

  • 什么是导航守卫

    • vue-router提供的导航守卫主要用来监听监听路由的进入和离开的.
    • vue-router提供了beforeEach和afterEach的钩子函数, 它们会在路由即将改变前和改变后触发.

全局前置守卫

使用router.beforeEach注册一个全局前置守卫:

const router = new VueRouter({ ... })

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

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。

每个守卫方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
    • next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
    • next(‘/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: ‘home’ 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
    • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

实例: 发生跳转时, 修改title

import Vue from 'vue'
import Router from 'vue-router'

// 1. 通过Vue.use安装插件
Vue.use(Router)

// 在这里导入, 然后在下面引用, 或者在下面component中直接引用也可以
const About = () => import('../components/About')
const User = () => import('../components/User')
const Home = () => import('../components/Home')
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')
const Profile = () => import('../components/Profile')


// 2. 将下面的router拆除出来,单独创建VueRoute对象
const routes= [
  {
    path: '/',
    redirect: '/helloWorld',

  },
  {
    path: '/helloWorld',
    component: () => import('../components/HelloWorld'),
    meta: {
      title: 'dashboard'
    }
  },
  {
    path: '/home',
    component: Home,
    redirect: "/home/news",
    children: [
      {
        path: "news",
        component: HomeNews,
        meta: {
          title: '新闻'
        }
      },
      {
        path: "message",
        component: HomeMessage,
        meta: {
          title: '消息'
        }
      }
    ]
  },
  {
    path: '/about',
    component: About,
    meta: {
      title: '关于'
    }
  },
  {
    path: '/user/:userId',
    component: User,
    meta: {
      title: '用户信息'
    }
  },
  {
    path: '/profile',
    component: Profile,
    meta: {
      title: '用户详情'
    }
  }
]

// 3. 创建VueRoute对象
const router = new Router({
  // 配置路径和组件的应用关系
  routes,
  mode: "history",
  linkActiveClass: "active"
})

router.beforeEach((to, from, next) => {
  // 从from跳转到to, 当路由发生跳转时:

  // 如果children中也定义了title, 那直接使用to.meta.title获取
  // 如果children没有定义title, 只有父路由定义了, 直接使用 to.meta.title 会变成undefined, 就需要使用 to.matched[0].meta.title 来获取父路由的title作为title
  document.title = to.meta.title
  console.log(to);
  next()
})

// 3.将router对象传入到Vue实例
export default router

全局后置钩子

你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:

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

全局解析守卫

在 2.5.0+ 你可以用router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

路由独享的守卫

路由独享的守卫与全局前置守卫的方法参数是一样的

你可以在路由配置上直接定义 beforeEnter 守卫:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

组件内的守卫

可以在路由组件内直接定义以下路由导航守卫:
– beforeRouteEnter
– beforeRouteUpdate (2.2 新增)
– 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`
  }
}

完整的导航解析流程

  1. 导航被触发。
  2. 在失活的组件里调用 beforeRouteLeave 守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
  5. 在路由配置里调用 beforeEnter。
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter。
  8. 调用全局的 beforeResolve 守卫 (2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

keep-alive

keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。

  • 它们有两个非常重要的属性:
    • include: 字符串或正则表达,只有匹配的组件会被缓存
    • exclude: 字符串或正则表达式,任何匹配的组件都不会被缓存
    <!-- 排除掉User,Profile组件 -->
    <keep-alive exclude="User,Profile">
      <router-view></router-view>
    </keep-alive>
  • router-view 也是一个组件,如果直接被包在 keep-alive 里面,所有路径匹配到的视图组件都会被缓存:

《vue-route 导航守卫和keep-alive》

点赞

发表评论

邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据