简体   繁体   中英

How can I pass data from vueJS to vuex

In this example, I'm using axios to fetch some data for me and then I need to pass these values and store it in Vuex

vue file with axios request:

<script>
    export default {
        data: function () {
            return {
                userData: {},
                login: {
                    username: '',
                    password: '',
                },
            }
        },
        computed: {
            loggedInUser() {
                return this.$store.state.loggedInUser;
            }
        },
        methods: {
            handleLoginFormSubmit() {
                // send axios request to controller and from controller to gRPC
                axios.post('/loginUser', this.login)
                    .then((response) => {
                        this.userData = JSON.parse(response.data[0]);
                    })
                // set loggedInUser info to vuex store
                this.$store.dispatch('loginUser',this.userData);
            }
        },
    }
</script>

when I inspect userData object is there with all info that I need now I have store.js file that should pass that userData and save it in Store but I always get empty object inside

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        loggedInUser: {
            firstName: '',
            lastName: '',
            email: '',
            uuid: '',
        }
    },
    getters: {
        loggedUser(state){
            return state.loggedInUser;
        }
    },
    mutations: {
        loginUser: (state, payload) => {
            state.loggedInUser.firstName = payload;
            state.loggedInUser.lastName = 1;
            state.loggedInUser.email = 1;
            state.loggedInUser.uuid = 1;
        }
    },
    actions: {
        loginUser: (context, payload) => {
            setTimeout(function () {
                console.log(payload);
                context.commit('loginUser', payload)
            }, 3000)
        }
    }
});

my mutation looks like this

type:"loginUser"

payload:Object (empty)

where did I do something wrong?

You dispatch before the data has returned. Move the dispatch into the callback.

handleLoginFormSubmit() {
  // send axios request to controller and from controller to gRPC
  axios.post('/loginUser', this.login)
    .then((response) => {
      this.userData = JSON.parse(response.data[0]);
      this.$store.dispatch('loginUser',this.userData);
    })
}

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