简体   繁体   中英

store is not defined vue.js

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

  },
});

change export type in UserStore like this:

line

export default new Vuex.Store({

replace with

export const store = new Vuex.Store({

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM