从VueRouter访问Vuex状态

时间:2020-04-15 18:23:14

标签: laravel vue.js vuex

我正在为vue.js的Navigation Guards缠上我的头。我尝试遵循该示例,但是我认为在将State(store.js)连接到路由器(routes.js)方面存在不足。在我的Login.vue组件中,我尝试将loadUser调度到State之后将其推送到新路由,然后将isLoggedIn更新为true。在我使用mapState的vue组件中,我需要在route.js中做同样的事情。也许有更好的方法可以做到这一点。为了提供完整的图片,我在Sanctum中使用vue前端和laravel后端。

从route.js中提取

const routes = [
    {
        path: '/',
        component: Login,
        name: 'login'
    },
    {
        path: '/dashboard',
        component: Dashboard,
        name: 'dashboard',
        meta: { requiresAuth: true }
    },
]

const router = new VueRouter({
    mode: 'history',
    routes // short for `routes: routes`
});

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

export default router;

从store.js中提取

export default {
    state : {
        isLoggedIn: false,
    }
}

从Login.vue中提取

methods : {
        async login() {
            this.loading = true;
            this.errors = null;

            try {
                await axios.get('/sanctum/csrf-cookie');
                await axios.post('/login', this.user);

                logIn();
                this.$store.dispatch('loadUser');
                this.$router.push({ name: 'logbook'});

            } catch (error) {
                this.errors = error.response && error.response.data.errors;
            }

            this.loading = false;
        }
    },

1 个答案:

答案 0 :(得分:2)

如果要访问/更改VueRouter中的Vuex,则必须使用命令router.app.store.state...

例如:

const routes = [
  { path: '/', component: Login, name: 'login' },
  { path: '/dashboard', component: Dashboard, name: 'dashboard', meta: { requiresAuth: true } },
];

const router = new VueRouter({
  mode: 'history',
  routes,
});

router.beforeEach((to, from, next) => {
  if (router.app.$store) {
    // Example to access the state
    console.log(router.app.$store.state.isLoggedIn);

    // Example to exec the mutation
    router.app.$store.commit('myMutation', 'myArgs');

    // Example to exec the action (ATTENTION IS ASYNC)
    router.app.$store.dispatch('myAction', 'myArgs');
  }

  if (to.meta.requiresAuth) {
    // ...
  } else {
    next();
  }
});

export default router;

注意: 您必须先加载Vuex,然后再加载VueRouter。因为,当VueRouter加载时,Vuex需要准备好。您可以在main.js中进行更改:

import Vue from 'vue'
import App from './App.vue'
import store from './store' // FIRST IMPORT
import router from './router' // SECOND IMPORT

Vue.config.productionTip = false

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

另外,我更喜欢控制cookie的登录,因为用户可以打开许多选项卡。我认为,您可以做自己喜欢的事。