zoukankan      html  css  js  c++  java
  • 路由的全局前置守卫

     1 router.beforeEach((to, from, next) => {
     2   // 获取仓库里的登录信息
     3   const auth = router.app.$options.store.state.auth
     4 
     5   if (auth && to.path.indexOf('/auth/') !== -1) {
     6     // 如果当前用户已登录,且目标路由包含 /auth/ ,就跳转到首页
     7     next('/')
     8   } else {
     9     next()
    10   }
    11 })
    • 使用 router.beforeEach 注册一个全局前置守卫,它在导航被触发后调用,我们可以通过跳转或取消的方式守卫导航,参数我们上面介绍过;
    • 使用 router.app 可以获取 router 对应的 Vue 根实例,使用实例的 $options.store 可以从选项中访问仓库;
    • 使用 next('/') 或者 next({ path: '/' }) 来跳转到一个新的地址;
    • 实例的 $options 是用于当前 Vue 实例的初始化选项:
    • new Vue({
        el: '#app',
        router,
        store,
        components: { App },
        template: '<App/>',
        created() {
          console.log(this.$options.el) // => '#app'
        }
      })

      在路由配置文件中,我们还可以通过下面的方式访问仓库:

    • import store from '../store'
      const auth = store.state.auth
  • 相关阅读:
    正则表达式入门教程
    js获取class
    锋利的jQuery第6章 jQuery与Ajax的应用
    显示隐藏左侧菜单
    unicode转为汉字
    $.ajax
    .ashx文件
    c#正则表达式
    调试发现的小错误
    sql2005连接不到本地数据库
  • 原文地址:https://www.cnblogs.com/yangguoe/p/9309889.html
Copyright © 2011-2022 走看看