store is not defined vue.js

半世苍凉 提交于 2021-01-28 09:41:14

问题


I have created login page. router intercepting the request and validates the user is authenticated or not . store is maintaining the user is logged in or not.

while debugging i am getting in auth.js

"store is not defined"

I also tried relative path instead of @ in imports.

router code snippet

      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 is like service which will interact with store and maintain state .

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();
  },
};

here is my store to

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: {

  },
});

回答1:


change export type in UserStore like this:

line

export default new Vuex.Store({

replace with

export const store = new Vuex.Store({


来源:https://stackoverflow.com/questions/47472401/store-is-not-defined-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!