A
A
Alex2019-10-13 14:31:49
Vue.js
Alex, 2019-10-13 14:31:49

How to make a request through Vuex?

Good afternoon, there is a component and in it a request via axios to api and getting user id data

<template>
    <li class="state_account_id">
        ID: {{params.id}}
    </li>
</template>

import axios from 'axios'
    export default {
        name: 'IdWeb',
        data () {
            return {
                params:null
            }
        },
        mounted() {
            axios
                .get('/information/account')
                .then(response => (this.params = response.data));
        }
    }

There is a connected store vuex
import Vue from 'vue'
import axios from 'axios'
import vuex from 'vuex'
Vue.use(vuex, axios);

export default new vuex.Store({
    state: {
    },
    actions: {
    }
});

Actually the question is how to make a request through vuex and display the id in the component. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2019-10-13
@astrodeep

Make an action in which to execute the request.

actions.loadMenu     = async ({ commit, state }, payload) => {
    if (!state.menus[payload.menu] || payload.force) {
        let response = await Vue.axios.get('/menu/' + payload.menu);
        if (response.status === 200) {
            commit('setMenu', { menu: payload.menu, data: response.data });
        }
    }
};

import axios from 'axios';
export default new vuex.Store({
    state: {
        params: null,
    },
    mutations:{
        setParams(state, payload){
            state.params = payload;
        }
    },
    actions: {
        async getParams({comit, state}){
            let response = await axios.get('information/account');
            if (response.status === 200) {
                commit('setParams', response.data);
            }
        }
    }
});

import { mapState } from 'vuex';
export default {
    name: 'IdWeb',
    computed: {
        ...mapState([
            'params'
        ])
    },
    mounted() {
        this.$store.dispath('getParams');
    },
}

<template>
    <li class="state_account_id" v-if="params">
        ID: {{params.id}}
    </li>
</template>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question