首页 > 解决方案 > 使用 vuex 操作发送的数据返回未定义

问题描述

我正在将 axios 与 vuex 一起使用,我需要使用 json 表单发送数据以执行发布请求并使用 axios 添加新行,我正在使用 vuex,当触发操作时,它不会保留数据并在操作时发送它,数据 json 是在 vue 组件上创建的,但不要将其发送到执行 axios post 的操作:

动作.js:

export const addClassification = ({data}) => {
    console.log('data actio:', {data})
    axios
    .post("/vendor/classification/save", data, {
        headers: {
            "Content-Type": "application/json",
            //  withCredentials: true //sent with cookie
            Authorization: "Bearer " + Vue.$cookies.get("jwt"),
        }
    })
    .then((res) => {
        console.log('res', res)
        // commit("ADD_TO_CLASSIFICATION", data);
    })
    .catch((err) => {
        console.log(err);
    });

state.js:

export default {
    vendorClassificationList: [],
}

页面.vue:

<BaseButton
    label="Modifier"
    classValue="btn-outline-primary"
    @click.native="addClassificationData"
/>
data() {
    return {
        submitStatus: "",
        name: this.$route.params.name,
        id: this.$route.params.id,
        code: this.$route.params.code,
        jsonData:[]
    };
},
methods: {
    ...mapActions(["addClassification"]),
    addClassificationData() {
        this.jsonData = JSON.stringify({
            id: null,
            name: this.name,
            code:this.code,
            active:true
        })
        console.log('json is', this.jsonData)
        this.addClassification({
            data : this.jsonData
        })
    },

标签: vue.jsvuejs2vuexvuex-modules

解决方案


Actions 是 Vuex 接收 vuex 上下文作为第一个参数,如您在 docs中所见。

换句话说,如果您在 Action.js 中进行更改:

addClassification = ( {data}) => {

addClassification = (vuexContext, {data}) => {

它应该可以解决问题。您可以调用 param vuexContext, context,如果需要,可以对其进行解构,或者_在未使用时调用它(如您的情况),只要它存在就无关紧要。


推荐阅读