E
E
ezpy2017-08-06 16:36:13
Vue.js
ezpy, 2017-08-06 16:36:13

How to properly work with vuex modules?

Hello, I can not understand how to work with modules correctly.
I've read the documentation but still can't figure it out.
For example, here is the storage code:

import Vue from 'vue'
import Vuex from 'vuex'
import VueAxios from 'vue-axios'
import VueResource from 'vue-resource'

Vue.use(VueResource)
Vue.use(Vuex)

const Profile = {
  state: { 
    login: '',
  },
  mutations: {
        SetLogin(state, dataJsonFromProfile) {
           state.login = dataJsonFromProfile.Login
        } 
    },
  actions: {
       checksession(context) {
            Vue.http.get('mydomain.ru/api/checksession').then(response => {

                if (response.data == 'true') {
                    Vue.http.get('mydomain.ru/api/getuserinfo').then(response => {

                        var getUserInfoJson = JSON.parse(JSON.stringify(response));

                        var makeParseJson = JSON.parse(getUserInfoJson.bodyText);
                        
                        context.commit('SetLogin',  makeParseJson)
                    }, response => {
                        // error callback
                    });
                }

            }, response => {
                // error callback
            });
        } 
    }
}

export const store = new Vuex.Store({
    strict: process.env.NODE_ENV !== 'production',
    state: {
        online: 2,
        ws: null,
    },

    actions: {
        setWs({commit}, query) {
            this.ws = new WebSocket(query)
            this.ws.onopen = function () {
                console.log('connect ws')
            }
        },
    }
})

Before I started to divide into modules, everything worked fine.
Now I want to
get the state data from the Profile module with App.vue
created: function () {
      this.$store.dispatch('checksession');
    },

    computed: {
        login () {
            return this.$store.state.login;
        }
    },

Actions is called through dispatch and pass the test, but I can’t figure out how to get the state.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kulakov, 2017-08-06
@ezpy

You need to bind the module instance to vuex:

const store = new Vuex.Store({
  modules: {
   profile: Profile
  }
})

and then state can be obtained by calling:
this.$store.state.profile.login

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question