简体   繁体   中英

How to change vuex state with mutations

I'm working on an app, where I'm trying to change Vuex state with mutations, but it doesn't seem to work. At first, state.status is an empty string, and I want to update it to token variable which is also a string. So in updateToken mutation I tried to achieve this. I have also tried something like Vue.set(state, 'status', token); , but it also doesn't work (here I had an error: "Cannot read property 'set' of undefined" ). When I'm trying to send token to the second mutation, it's still empty, but console.log() prints the correct token.

Here is my store.js code:

import { createStore } from 'vuex';
import axios from "axios"

const msgFormData = new FormData();

const store = createStore({
    state: {
        status: "",
    },
    mutations: {
        updateToken(state, token) {
            state.status = token
        },
        sendToken(state, user_name) {
            msgFormData.set('user_name', user_name);
            msgFormData.append('msg_token', state.status);

            axios.post("http://someip/index.php", msgFormData)
            .then(res => {
                console.log(res.status)
            })
            .catch(error => {
            console.log(error)
            })
        },
    }
});

export default store;

I'm calling these mutations like this: this.$store.commit('updateToken', token.value) in some vue file and this.$store.commit('sendToken', this.user.email) in App.vue .

I don't know where I'm doing a mistake, can anybody help please?

  1. Use an action instead of a mutation for asynchronous operations like sendToken
  2. Move const msgFormData = new FormData(); into the sendToken method to create a new instance of FormData upon each invocation of the method

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