R
R
Ruslan Absalyamov2018-11-26 15:56:03
Vue.js
Ruslan Absalyamov, 2018-11-26 15:56:03

Why can't I access getters?

Why can't I access the getter in vuex.
my store code

import Vuex from 'vuex';
import Vue from 'vue';
import rest from './rest/api';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        user: null
    },
    mutations: {
        userState (state, payload) {
            state.user = payload;
        }
    },
    actions: {
        getUser(context) {
            let user = new rest('user.json');
            user.list().then(res => {
                context.commit('userState', res.data)
            })
                .catch(err => console.error(err));
        }
    },
    getters: {
        profile: state => {
            return state.user;
        }
    }
})

main.js
...
//Подключаю хранилище
import store from './store';

store.dispatch('getUser');
new Vue({
    el: '#app',
    router: router,
    components:{
        'head-app':headImplant,
        'footer-app':footer,
        'sidebar-app': sidebar
    }
});

In the component I call this getter
<script>
    import store from '../../store'
    export default {
        name: "head",
        created: function () {
            console.log(store.getters.profile);
        }
    }
</script>

It shows null for me, although if I call store.getters
5bfbed54f1457652384881.png
Then it comes out for me

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-11-26
@0xD34F Vue.js

call this getter <...> shows null

This means that the data has not yet loaded by the time you pull the getter, that's all. There is nothing here to tell fairy tales about "it does not work." Everything is OK.

E
Evgeny Kulakov, 2018-11-26
@kulakoff Vue.js

Perhaps the action has not worked yet. Do this to check:

store.dispatch('getUser').then(() => {
new Vue({
    el: '#app',
    router: router,
    components:{
        'head-app':headImplant,
        'footer-app':footer,
        'sidebar-app': sidebar
    }
})
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question