如何通过突变改变 vuex 状态

How to change vuex state with mutations

我正在开发一个应用程序,我试图在其中使用突变来更改 Vuex 状态,但它似乎不起作用。起初, state.status 是一个空字符串,我想将其更新为 token 变量,这也是一个字符串。所以在 updateToken 突变中我试图实现这一点。我也试过 Vue.set(state, 'status', token); 之类的东西,但它也不起作用(这里我有一个错误:"Cannot read property 'set' of undefined")。当我尝试将 token 发送到第二个突变时,它仍然是空的,但是 console.log() 打印出正确的标记。

这是我的 store.js 代码:

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;

我这样称呼这些突变: this.$store.commit('updateToken', token.value) 在一些 vue 文件中和 this.$store.commit('sendToken', this.user.email)App.vue.

我不知道我哪里做错了,有人可以帮忙吗?

  1. 使用 action 而不是像 sendToken
  2. 这样的异步操作的突变
  3. const msgFormData = new FormData(); 移动到 sendToken 方法中以在每次调用方法时创建 FormData 的新实例