解决Vue路由之前访问Vuex

时间:2018-09-20 08:04:17

标签: vue.js axios vuex vue-router

我有什么:

  1. 具有经过身份验证的路由和公共路由的路由器
  2. 具有用户身份验证状态的vuex

我想要什么:使用axios向服务器发送请求,以在加载应用程序之前(在解决路由器之前)检查用户的身份验证状态

router.js

import Vue from 'vue'
import Router from 'vue-router'
import store from './store'

Vue.use(Router)

const router = new Router({
  ...
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/account',
      name: 'account',
      component: () => import(/* webpackChunkName: "account" */ './views/Account.vue'),
      meta: {
        requiresAuth: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(route => route.meta.requiresAuth)) {
    if (store.state.authStatus)
      next()
    else
      next({name: 'home'})
  } else {
    next()
  }
})

export default router

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    authStatus: false
  },
  mutations: {
    setAuthStatus(state, authStatus) {
      state.authStatus = authStatus
    }
  }
})

 axios.get(...)
   .then(response => {
     store.commit('setAuthStatus', true)
   })

export default store

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

我的问题:当我获得授权时在浏览器中输入mydomain.com/acount(之前未加载应用)时,无论如何,我都重定向到了home。重定向后,我看到我已被授权(我在Home组件内设置了一些DOM元素,仅向授权用户显示)。


我尝试过,没有帮助:

store.js

const store = new Vuex.Store({
  ...
  actions: {
    setAuthStatus({commit}) {
      axios.get(...)
        .then(response => {
          commit('setAuthStatus', true)
        })
    }
  }
})

main.js

store.dispatch('setAuthStatus').then(() => {
  new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount('#app')
})

编辑:在main.js中,我尝试通过

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')

它也没有帮助。

3 个答案:

答案 0 :(得分:1)

在导航卫士中,您需要异步的内容,因此将axios Promise保存为authStatus在商店中。解决提交问题并设置登录状态时。 在导航卫士中,等待承诺得到解决,然后调用下一个函数以输入下一个路由器。

Store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    /*  EXAMPLE
    authStatus: new Promise(resolve => {
      setTimeout(() => {
        const requestResult = true;
        store.commit("setAuthStatus", requestResult);
        resolve(requestResult);
      }, 1000);
    }),
    */
    authStatus: axios.get(...).then((requestResult) => {
        store.commit("setAuthStatus", requestResult);
    }),
    loggedIn: false
  },
  mutations: {
    setAuthStatus(state, loggedIn) {
      state.loggedIn = loggedIn;
    }
  }
});

export default store;

router.js

router.beforeEach((to, from, next) => {
  if (to.matched.some(route => route.meta.requiresAuth)) {
    store.state.authStatus.then(loggedIn => {
      if (loggedIn) next();
      else next({ name: "home" });
    });
  } else {
    next();
  }
});

检查此解决方案是否有效here

答案 1 :(得分:1)

绕着Vanojx1's answer,我用下一个解决了我的问题。

store.js

const store = new Vuex.Store({
  state: {
    authStatus: axios.get(...).then(response => {
      store.commit('setAuthStatus', true)
    }),
    userAuth: false
  },
  mutations: {
    setAuthStatus(state, authStatus) {
      state.userAuth = authStatus
    }
  }
})

router.js

router.beforeEach((to, from, next) => {
  if (to.matched.some(route => route.meta.requiresAuth)) {
    store.state.authStatus.then(() => {
      //we're getting 200 status code response here, so user is authorized
      //be sure that API you're consuming return correct status code when user is authorized
      next()
    }).catch(() => {
      //we're getting anything but not 200 status code response here, so user is not authorized
      next({name: 'home'})
    })
  } else {
    next()
  }
})

答案 2 :(得分:0)

问题可能是由于您输入网址时 https://example.com/account

它启动应用程序,并且axios对服务器执行异步请求。 因此,也许您应该尝试从beforeEach内部进行axios调用。

通过这种方式,您可以轻松验证用户身份。

问题是您无法使axios同步,因此必须与axios返回一个promise才能实现功能。

请告诉您这是否对您有帮助。