Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 如何在导航卫士之前调用方法_Vue.js_Vuex_Vue Router - Fatal编程技术网

Vue.js 如何在导航卫士之前调用方法

Vue.js 如何在导航卫士之前调用方法,vue.js,vuex,vue-router,Vue.js,Vuex,Vue Router,我想知道我是否可以在navigation guard之前调用函数。 当用户登录时,my API返回一个用户对象,其中包含一个访问令牌(存储在内存中)和一个刷新令牌(仅存储在cookie http中)。 刷新页面时,如果存在有效的刷新令牌,我的API将返回一个带有新访问令牌的用户对象,但我不知道如何在导航保护之前执行此操作。我的导航卫士只是一个beforeach方法,它检查存储中是否有用户对象,如果没有用户对象,它将返回登录页面。假设在调用API之前调用了guard,那么guard总是将用户发送到

我想知道我是否可以在navigation guard之前调用函数。 当用户登录时,my API返回一个用户对象,其中包含一个访问令牌(存储在内存中)和一个刷新令牌(仅存储在cookie http中)。 刷新页面时,如果存在有效的刷新令牌,我的API将返回一个带有新访问令牌的用户对象,但我不知道如何在导航保护之前执行此操作。我的导航卫士只是一个beforeach方法,它检查存储中是否有用户对象,如果没有用户对象,它将返回登录页面。假设在调用API之前调用了guard,那么guard总是将用户发送到登录路由

这里是路由器:

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;
我想在路由器之前调用下面的刷新函数,并使用返回新用户对象的API调用调用beforeach方法(而不是在路由之前)来持久化登录

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

我不确定这正是你的情况,但对我来说,类似这样的做法奏效了:

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')
      }
   },
]

在这种情况下,用户在未登录的情况下只能看到主页。

请添加
VueRouter
对象好吗?