【问题标题】:How to access namespaced vuex inside router如何访问路由器内的命名空间vuex
【发布时间】:2020-09-29 09:43:05
【问题描述】:

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

这里是示例代码。

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');

是的,当我尝试验证用户是否通过控制台日志登录时总是返回空值,而我已经在这个问题上坚持了 1 个小时,谁能帮我解决这个问题?

【问题讨论】:

  • 你的认证模块的state在哪里?
  • 您是否将登录信息存储为持久值,我的意思是,在本地存储中,一旦您重新加载页面,登录信息仍然存在吗?
  • @Phil,对不起,我编辑了它,只是没有,状态是这样的
  • @AndresForonda,即使在 devtools 中也是如此
  • 将所有状态属性初始化为null,当您尝试访问getter 时,如果其中任何一个为null,则结果将为null。两个问题...... 1)您的身份验证模块的突变在哪里,以及 2)您在哪里提交它们?

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


【解决方案1】:

您只是将您的商店与本地存储同步。您还需要坚持它以使其在重新加载等后继续存在,

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

【讨论】:

    【解决方案2】:

    也许您在 "back/me" 上出现错误?

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2017-11-09
      • 2017-12-21
      • 2012-01-25
      相关资源
      最近更新 更多