【问题标题】:store is not defined vue.js商店未定义 vue.js
【发布时间】:2017-11-24 11:30:35
【问题描述】:

我已经创建了登录页面。路由器拦截请求并验证用户是否经过身份验证。 store 正在维护用户是否登录。

在调试时我进入了 auth.js

“商店未定义”

我还在导入中尝试了相对路径而不是 @。

路由器代码sn-p

      import auth from '@/services/auth';
       ...
        router.beforeEach((to, from, next) => {
      if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!auth.loggedIn()) {
          next({
            path: '/login',
          });
        } else {
          next();
        }
      } else {
        next(); 
      }
    });

auth.js 就像服务,它将与存储交互并维护状态。

import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import store from '@/store/UserStore';

Vue.use(VueAxios, axios);

export default {
  login(credentials) {
    return new Promise((resolve, reject) => {
      Vue.axios.post('/api/authenticate', credentials).then((response) => {
        localStorage.setItem('token', response.body.token);
        store.commit('LOGIN_USER');
        resolve();
      }).catch((error) => {
        store.commit('LOGOUT_USER');
        reject(error);
      });
    });
  },
  isUserLoggedIn() {
    return store.isUserLoggedIn();
  },
};

这是我的商店

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  state: {
    isLogged: !localStorage.getItem('token'),
    user: {},
  },
  actions: {

  },
  mutations: {
    /*  eslint-disable no-param-reassign */
    LOGIN_USER(state) {
      state.isLogged = true;
    },
    /* eslint-disable no-param-reassign */
    LOGOUT_USER(state) {
      state.isLogged = false;
    },
  },
  getters: {
    isUserLoggedIn: state => state.isLogged,
  },
  modules: {

  },
});

【问题讨论】:

    标签: javascript vuejs2 vuex


    【解决方案1】:

    像这样在 UserStore 中更改导出类型:

    行

    export default new Vuex.Store({
    

    替换为

    export const store = new Vuex.Store({
    

    【讨论】:

      猜你喜欢
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2020-07-15
      • 2021-10-17
      • 2020-03-13
      • 2013-06-30
      • 1970-01-01
      相关资源
      最近更新 更多