首页 > 解决方案 > 如何访问路由器文件中的 Vuex 存储?Vue

问题描述

我想创建一个身份验证保护路线,但我需要一个商店来获取它 isLoggedIn。我是 Vuex 和 Vue 的初学者,我的商店位于 main.js 文件中。如果我尝试从路由器访问状态并且当我 console.log 它未定义时,我会收到此错误_main__WEBPACK_IMPORTED_MODULE_4__.default is undefined。我希望有人可以帮助我实现这一目标。

这是我的商店:

    import { createApp } from 'vue';
import { createStore } from 'vuex';
import router from './router';

import createPersistedState from 'vuex-persistedstate';
import Cookies from 'js-cookie';

import './bootstrap.min.css';
import App from './App.vue';
import API from './API';

const store = createStore({
  state: {
    posts: null,
    loading: null,
    error: null,

    user: {},
    token: null,
    userLoading: null,
    userError: null,

    registerLoading: null,
    registerError: null,

    logOutErorr: null,
  },
  plugins: [
    createPersistedState({
      key: 'BLOG_MEVN',
      paths: ['user', 'token'],
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: key => Cookies.remove(key),
      },
    }),
  ],

  getters: {
    isLoggedIn: state => !!state.token,
  },

  mutations: {
    SET_POSTS_LIST(state, payload) {
      state.posts = payload;
    },
    SET_POSTS_STATUS_LOADING(state, payload) {
      state.loading = payload;
    },
    SET_POSTS_LIST_STATUS_FAIL(state, payload) {
      state.error = payload;
    },

    SET_USER(state, payload) {
      state.user = payload;
      state.token = payload.token;
    },
    SET_USER_LOADING(state, payload) {
      state.userLoading = payload;
    },
    SET_USER_STATUS_FAIL(state, payload) {
      state.userError = payload;
    },

    USER_LOGOUT(state, payload) {
      state.user = payload;
      state.token = null;
    },
    USER_LOGOUT_FAIL(state, payload) {
      state.logOutErorr = payload;
    },

    USER_REGISTER(state, payload) {
      state.user = payload;
      state.token = payload.token;
    },
    USER_REGISTER_FAIL(state, payload) {
      state.registerError = payload;
    },
    USER_REGISTER_LOADING(state, payload) {
      state.registerLoading = payload;
    },
  },
  actions: {
    async getPosts({ commit }) {
      commit('SET_POSTS_STATUS_LOADING', true);
      commit('SET_POSTS_LIST', []);
      try {
        const { data } = await API.get('/api/v1/posts');
        commit('SET_POSTS_LIST', data);
        commit('SET_POSTS_STATUS_LOADING', false);
      } catch (error) {
        commit('SET_POSTS_STATUS_LOADING', false);

        commit(
          'SET_POSTS_LIST_STATUS_FAIL',
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message
        );
      }
    },

    async login({ commit }, User) {
      commit('SET_USER_LOADING', true);
      commit('SET_USER', []);
      try {
        const config = {
          headers: {
            'Content-Type': 'application/json',
          },
        };

        const { data } = await API.post(`/api/v1/users/login`, User, config);
        commit('SET_USER', data);
        commit('SET_USER_LOADING', false);
      } catch (error) {
        commit('SET_USER_LOADING', false);

        commit(
          'SET_USER_STATUS_FAIL',
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message
        );
      }
    },

    async register({ commit }, User) {
      commit('USER_REGISTER_LOADING', true);
      commit('USER_REGISTER', []);
      try {
        const config = {
          headers: {
            'Content-Type': 'application/json',
          },
        };

        const { data } = await API.post(`/api/v1/users/signup`, User, config);
        commit('USER_REGISTER', data);
        commit('USER_REGISTER_LOADING', false);
      } catch (error) {
        commit('USER_REGISTER_LOADING', false);

        commit(
          'USER_REGISTER_FAIL',
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message
        );
      }
    },

    async logout({ commit }) {
      try {
        await API.get(`/api/v1/users/logout`);
        commit('USER_LOGOUT', {});
      } catch (error) {
        commit(
          'USER_LOGOUT_FAIL',
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message
        );
      }
    },
  },
});

export default store;   <------- here

const app = createApp(App);

app.use(router);
app.use(store);

app.mount('#app');

路由器文件

import { createRouter, createWebHistory } from 'vue-router';
import Home from '../screens/Home.vue';
import Login from '../screens/Login.vue';
import Register from '../screens/Register.vue';

import store from '../main';

console.log(store);

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

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

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

export default router;

标签: vue.jsvuexvue-router

解决方案


存储(通常是“store/index.js”):

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
    state: {...}
    getters: {...}
    ...
});

路由器(通常是“router/index.js”):

import Vue from 'vue';
import VueRouter from 'vue-router';
import store from 'path/to/your/store';
Vue.use(VueRouter);
const routes = [...];
export default new VueRouter({...});
...
//Now you can use your store
store.getters['nameOfGetter'];

推荐阅读