【问题标题】:How to call a method before navigation guard如何在导航守卫之前调用方法
【发布时间】:2020-11-02 04:27:08
【问题描述】:

我想知道我是否可以在导航守卫之前调用一个函数。 当用户登录时,我的 API 返回一个带有访问令牌(存储在内存中)和刷新令牌(仅存储在 cookie http 中)的用户对象。 刷新页面时,如果存在有效的刷新令牌,我的 API 会返回一个带有新访问令牌的用户对象,但我不知道如何在导航守卫之前执行此操作。我的导航守卫只是一个 beforeEach 方法,它检查商店中是否有用户对象,如果没有用户对象,它会返回登录页面。鉴于在调用 API 之前调用了守卫,守卫总是将用户发送到登录路由

这里是路由器:

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    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"),
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach(async (to, from, next) => {
  if (to.name !== "Login" && !store.getters.user.userId) {
    next({ name: "Login" });
  } else next();
});

export default router;

我想在路由器和 beforeEach 方法(不是在路由之前)之前调用下面的刷新函数,以使用返回新用户对象的 API 调用来持久登录

 async refresh({ commit }) {
        let response = await axios.post(user_uri + "refresh_token");
        commit("setUser", response.data);
      },

【问题讨论】:

  • 能否添加您的VueRouter 对象?

标签: vue.js vuex vue-router


【解决方案1】:

我不确定你的情况,但对我来说,这样的事情有效:

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


let checkLogin = async (to, from, next) => {
    if (from.fullPath === "/") {
        await getToken() // 
    }
    next()
}

let getToken= async () => {
   //....
}


const routes = [
   {path: '/', component: homeScreen},
   {
      path: '/your-path', component: yourComponent,
      children: [...],
      async beforeEnter(to, from, next) {
          if (//chack if logged in) next()
          else
              vue.$router.push('/login')
      }
   },
]

在这种情况下,用户无需登录就只能看到主页。

【讨论】:

    最近更新 更多