D
D
Dmitry Kuznetsov2018-01-29 08:37:13
Vue.js
Dmitry Kuznetsov, 2018-01-29 08:37:13

Why doesn't Vuex work in a separate file?

Good day!
Having dealt with the question Why "Cannot read property 'authCheck' of undefined"? (xs how it happened), a new problem appeared. The matter is that I have a separate file in which there are some actions with the data (something like "models" in php). In one of the methods, I use Vuex to get the data, but for some reason the console swears like this:

Cannot read property 'state' of undefined
.
main.js :
main.js
// Главные модули
import Vue from 'vue'
import VueRouter from 'vue-router'
import VeeValidate from 'vee-validate'
import axios from 'axios'
import VueAxios from 'vue-axios'
import Vuex from 'vuex'

Vue.use(VueRouter)
Vue.use(VeeValidate)
Vue.use(VueAxios, axios)
Vue.use(Vuex)

// Второстепенные модули
import App from './App.vue'
import store from './store'
import router from './router'

// Модули для работы с данными
// import AuthUser from './packages/AuthUser.js'
// Vue.use(AuthUser)

// Styles
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.css'
Vue.use(Vuetify)

// Настройка модулей
axios.defaults.baseURL = 'http://api.site.ru/'; // Базовый URL адрес
axios.defaults.headers.common['X-CSRF-TOKEN'] = 'Bearer ' + '*********************************';    // Токен

Vue.config.productionTip = false

new Vue({
    el: '#app',
    render: h => h(App),
    router,
    store
})
router.js :
router.js
import Vue from 'vue';
import VueRouter from 'vue-router'
import Meta from 'vue-meta'

Vue.use(VueRouter)
Vue.use(Meta)

import Home from '../components/Home.vue'
import News from '../components/News.vue'
import Games from '../components/Games.vue'

import Users from '../components/Users/Users.vue'
import Logout from '../components/Users/Logout.vue'

import NotFound from '../components/pages/NotFound.vue'

// Авторизация
import Login from '../components/Auth/Login.vue'
import Register from '../components/Auth/Register.vue'

const router = new VueRouter({
    mode: 'history',
    routes: [
        /* Нейтральные страницы */
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/news',
            name: 'news',
            component: News,
        },
        {
            path: '/games',
            name: 'games',
            component: Games,
        },

        /* Для пользователей */
        {
            path: '/users/:id',
            name: 'users',
            component: Users,
            meta: {
                isAuth: true
            },
        },
        {
            path: '/logout',
            name: 'users.logout',
            component: Logout,
            meta: {
                isAuth: true
            }
        },

        /* Для гостей */
        {
            path: '/auth/login',
            name: 'auth.login',
            component: Login,
            meta: {
                isAuth: false
            }
        },

        {
            path: '/auth/register',
            name: 'auth.register',
            component: Register,
            meta: {
                isAuth: false
            }
        },

        /* Web-серверные ошибки и сообщения */
        {
            /* 404 - Page not found */
            path: '/404',
            name: 'notfound',
            component: NotFound
        }, {
            path: '*',
            redirect: '/404'
        }
    ],

    linkActiveClass: '',
    linkExactActiveClass: ''
})

router.beforeEach(
    (to, from, next) => {
        if(to.matched.some(record => record.meta.isAuth)){
            if(store.state.Auth.auth){
                next({
                    path: '/'
                })
            } else next()
        }else if(to.matched.some(record => record.meta.isAuth)){
            if(!store.state.Auth.auth){
                next({
                    path: '/auth/login'
                })
            }else{
                next()
            }
        } else next()
    }
)

export default router

store.js :
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

import Auth from './modules/Auth.js'

Vue.use(Vuex)

const store = new Vuex.Store({
    plugins: [ createPersistedState({ storage: window.sessionStorage }) ],

    modules: {
        Auth: Auth
    },
})

export default store
Module for store.js - Auth.js :
Auth.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const Auth = new Vuex.Store({
    state: {
        auth: false,    // Авторизован ли пользователь
        user: {},   // Данные о пользователе
        token: {},  // Токен для API
    },

    mutations: {
        /**
         * Сохраняем данные токена
         * @param state
         */
        tokenAuth: (state, token) => {
            state.token = token
        },

        /**
         * Сохраняем информацию о том, что пользователь авторизован
         * @param state
         * @param data
         */
        auth: (state, data) => {
            state.auth = true
            state.user = data
        },

        /**
         * "Выходим" из аккаунта и удаляем все данные с auth()
         * @param state
         */
        logout: (state) => {
            state.auth = false
            state.user = {}
            state.user = {}
        }
    },
})

export default Auth

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
akass, 2018-01-30
@dima9595

You need to move the Auth logic to the vuex module and work with it. Details in the comments to the question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question