【问题标题】:Laravel + Vuejs have trouble with async problemLaravel + Vuejs 遇到异步问题
【发布时间】:2020-11-05 01:55:02
【问题描述】:

我的 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 “已验证”工作正常(如果用户连接则为 true,否则为 false)。

但在我的路由器中,所有时间都采用存储中设置的默认值(null)。我知道为什么,因为如果我重新加载页面 0.5 秒,则商店状态为 null,然后学习 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();
        }
      });
    }
  }

【问题讨论】:

  • 有点难以追查问题所在。我建议你下载 Vue devtools(浏览器插件 firefox/chrome),这样你就可以查看它运行时的状态。
  • 确实很难跟踪,开发工具肯定会有所帮助,我注意到您的商店没有定义为函数/闭包,而是作为静态对象,如果您重新导入可能会发生冲突它在商店里。导致为空。此外,请确保您在路由器中导入了商店。并且您可以检查模块是否已加载。全部。 (也 vue devtools 使这更容易)
  • 您的商店模块是商店主入口点中的固定模块,还是您动态加载它..这也可能导致这些问题..
  • 是的,我使用了 devtools,我看到 vuex 状态在 0.5 秒内为空,并在之后设置。但是现在直接在我的路由器中设置 store.dispatch 方法可以正常工作。我只是不知道是否有更好的方法来做到这一点。谢谢你的回复!

标签: laravel vue.js authentication asynchronous synchronization


【解决方案1】:

我更清楚地回答了等待商店多么容易!

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

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

设置为通常每次重新加载都这样做,但如果我输入一个 console.log,我看到路由器正在执行,并且在“尝试”操作被执行之后。

所以在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
    }
  })
})

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

I'm not sur 显然是最好的方法。但是是工作,我认为这不是一个坏方法!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多