如何在路由器内部访问命名空间的vuex

时间:2020-06-10 04:11:48

标签: vue.js vuex vue-router vuex-modules

我尝试使用routers.js中带有命名空间的模块访问vuex吸气剂,但是当值是true(用户登录)时,吸气剂总是返回空值

这是示例代码。

store / index.js

import Vue from 'vue';
import Vuex from 'vuex';
import auth from './auth'

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    auth
  }
});

store / auth / index.js

import axios from "axios"

export default {
  namespaced: true,
  state: {
    token: null,
    user: null,
    status: null
  },

  getters: {
    authenticated(state) {
      return state.token && state.user && state.status;
    },

    user(state) {
      return state.user;
    }
  },

  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
    },
    SET_USER(state, data) {
      state.user = data;
    },
    SET_STATUS(state, status) {
      state.status = status
    }
  },

  actions: {
    async logIn({ dispatch }, data) {
      let response = await axios.post('back/in', data);

      return dispatch('attemptLogin', response.data.token)
    },

    async attemptLogin({ commit, state }, token) {
      if (token) {
        commit('SET_TOKEN', token);
        commit('SET_STATUS', true);
      }

      if (!state) {
        return
      }

      try {
        let response = await axios.get('back/me')

        commit('SET_USER', response.data.user)
      } catch (e) {
        commit('SET_USER', null)
        commit('SET_TOKEN', null)
        commit('SET_STATUS', null);
      }
    }
  },

}

store / subscriber.js

import store from '../store'
import axios from 'axios'


store.subscribe((mutation) => {
  switch (mutation.type) {
    case 'auth/SET_TOKEN':
      if (mutation.payload) {
        axios.defaults.headers.common['Authorization'] = `Bearer  ${mutation.payload}`;
        localStorage.setItem('token', mutation.payload)
      } else {
        axios.defaults.headers.common['Authorization'] = null;
        localStorage.setItem('token')
      }

      break;

    default:
      break;
  }
})

router.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '../views/Login';
import LoggedInLayout from '../layouts/LoggedInLayout';
import Dashboard from '../views/Dashboard';
import Post from '../views/pages/Post/Index';
import store from '../store'


Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      title: 'Login Page',
      path: '/backend/login',
      name: 'login',
      component: Login,
      meta: {
        mustLoggedIn: true
      }
    },
    {
      path: '/backend',
      component: LoggedInLayout,
      children: [
        {
          title: 'Dashboard',
          path: '/backend/dashboard',
          name: 'dashboard',
          component: Dashboard
        },
        {
          path: '/backend/post',
          name: 'post',
          component: Post
        },
      ],
      meta: {
        mustLoggedIn: true
      }
    },

  ]
});


router.beforeEach(async (to, from, next) => {
  if (to.matched.some(record => record.meta.mustLoggedIn)) {
    console.log(store.getters['auth/authenticated']); // and everytime i tried to console log, it always return null 
    if (!store.getters['auth/authenticated']) {
      next({
        path: '/backend/login'
      })
    } else {
      next('/backend/dashboard')
    }
  } else {
    next() 
  }
})

export default router;

app.js

require('./bootstrap');
import Vue from 'vue';
import store from './store';
import router from './router'
import MainApp from './layouts/MainApp.vue'
import axios from 'axios';
require('./store/subscriber')

axios.defaults.baseURL = 'http://127.0.0.1:8000/api/';

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

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

是的,当我尝试验证是否通过控制台日志登录用户时始终返回null值,并且我已经坚持了1个小时的问题,有人可以帮助我解决此问题吗?

2 个答案:

答案 0 :(得分:-1)

您正在将商店与本地存储同步。您还需要对其进行保存,以使其在重新加载后继续运行,等等。

您将需要使用类似vuex-persist的名称。 https://www.npmjs.com/package/vuex-persist

答案 1 :(得分:-1)

也许您在“ back / me”上遇到错误?

尝试在catch块中添加“ consol.error”!

但是,为什么登录页面的meta“ mustLoggedIn”设置为true?