Laravel + Vuejs 遇到异步问题

Laravel + Vuejs have trouble with async problem

我的 Vuejs/Laravel 应用程序出现异步问题。

如果用户已连接,我在 vuex 中有:我的状态用户和状态令牌。我在 localStorage 中设置了这个令牌,如果我的用户 F5(刷新页面),我可以用它重新登录他。

有我的商店(命名空间:auth):

export default {
    namespaced: true,
    state: {
        token: null,
        user: null
    },
    getters: {
        authenticated(state){
            return state.token && state.user;
        },
        user(state){
            return state.user;
        }
    },
    mutations: {
        SET_TOKEN(state, token){
            state.token = token;
        },
        SET_USER(state, data){
            state.user = data;
        },
    },
    actions: {
        async login({ dispatch }, credentials){
           let response = await axios.post(`/api/auth/connexion`, credentials);

           dispatch('attempt', response.data.token);
        }
        , 
        async attempt({ commit, state }, token) {
            if(token){
                commit('SET_TOKEN', token);
            }
            if (!state.token){
                return
            }
            try{
                let response = await axios.get(`/api/auth/me`);
                commit('SET_USER', response.data);
                console.log('Done')
            }
            catch(err){
                commit('SET_TOKEN', null);
                commit('SET_USER', null);
            }
        }
    }
}

我的app.js,我这样做是为了重新登录我当前的用户:

store.dispatch('auth/attempt', localStorage.getItem('token'));

并在路由器中完成路由:

{
    name: 'Login',
    path: '/',
    component: Login,
    beforeEnter: (to, from, next) => {
      console.log('Getter in router : ' + store.getters['auth/authenticated']);
      if (!store.getters['auth/authenticated']){
        next()
      }else {
        return next({
          name: 'Home'
        })
      }
    }
  }

问题出在哪里,如果我调用 Home.vue 我的 getter“已验证”工作正常(如果用户连接则为真,否则为假)。

但在我的路由器中,所有时间都采用存储中设置的默认值(空)。我知道这是为什么,因为如果我重新加载我的页面 0.5 秒,商店状态为空,之后学习 localStorage 并创建我的用户和令牌。

我想要的(我认为)是路由器等待我的操作尝试,然后他可以进行检查。

我已经学习了教程https://www.youtube.com/watch?v=1YGWP-mj6nQ&list=PLfdtiltiRHWF1jqLcNO_2jWJXj9RuSDvY&index=6

而且我真的不知道我需要做什么才能让我的路由器正常工作 =(

如果有人能给我解释一下,非常感谢!

更新:

如果我这样做了:

{
    name: 'Login',
    path: '/',
    component: Login,
     beforeEnter:async (to, from, next) => {
      await store.dispatch('auth/attempt', localStorage.getItem('token'));

      if (!store.getters['auth/authenticated']){
        next()
      }else {
        return next({
          name: 'Home'
        })
      }
    }

但我想了解我真正需要做什么,因为那不是一个明确的方法,真的很垃圾。

更新2:

如果有人有其他方法,也许我找到了最好的解决方案。

{
    name: 'Home',
    path: '/accueil',
    component: Home,
    beforeEnter: (to, from, next) => {
      store.dispatch('auth/attempt', localStorage.getItem('token')).then((response) => {
        if (!store.getters['auth/authenticated']){
          return next({
            name: 'Login'
          })
        }else {
          next();
        }
      });
    }
  }

我回答的更清楚 店家多轻松等!

在我的app.js之前我有这个:

store.dispatch('auth/attempt', localStorage.getItem('token'));

设置为 normaly 每次重新加载都这样做,但如果我放入 console.log,我看到路由器正在执行,并且在执行操作 'attempt' 之后。

所以在app.js中删除这一行,你可以在!

之后添加一个.then()
router.beforeEach((to, from, next) => {
  store.dispatch('auth/attempt', localStorage.getItem('token')).then(() =>{
    if (store.getters['auth/authenticated']){
      next();
    }else {
      //something other
    }
  })
})

因此我有相同的线路代码,但我可以对我的路由器说等待操作“尝试”。

我不确定 sur 显然是最好的方法。但这是工作,我认为这不是一个坏方法!