【问题标题】:Vuex action payload is undefinedVuex 动作负载未定义
【发布时间】:2020-04-01 16:14:19
【问题描述】:

我有一个看起来像这样的组件(简化):

<script>
import { mapActions } from 'vuex';
import router from '@/router';
import { bindingService } from '@/_services/binding.service';

export default {
    props: {
        serialNumber: { type: String, default: ' ' }
    },
    data: () => ({
        subscriptions: ['Loading...'],
        vin: null,
    }),
    computed: {
        splittedSerialNumber() {
            return this.serialNumber.split(' ')[0];
        }
    },
    created() {
        //fetch some data
        bindingService.fetchSomeData('xxx').then((data) => {
            this.vin = data;
        });        
    },
    methods: {
        ...mapActions('binding', ['setDeviceSerialNumber', 'setVehicleIdentificationNumber']),
        cancel() {
            router.push('/home');
        },
        ok() {
            console.log(this.vin);  //this console.log outputs valid data
            this.setVehicleIdentificationNumber(this.vin);
        },

    },
};
</script>

然后我的商店看起来像这样(简化):

const state = {
    vehicleIdentificationNumber: null,
};

const actions = {
  setVehicleIdentificationNumber({ commit }, { vin }) {
        console.log(vin); // this console.log outputs undefined
        commit('SET_VEHICLE_IDENTIFICATION_NUMBER', vin);
    }
};

const mutations = {
SET_VEHICLE_IDENTIFICATION_NUMBER(state, vin) {
        state.vehicleIdentificationNumber = vin;
    },
};

const binding = {
    namespaced: true,
    state,
    actions,
    mutations,
};

export default binding;

我更加困惑,因为我在这个项目中使用了几乎相同的动作和突变格式并且它们有效。 我没有想法,期待任何形式的输入:)

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    在组件上的 setVehicleIdentificationNumber 方法中,您将 vin 作为整数参数传递。

    在动作中,参数是一个对象:{ vin }

    将action参数改为vin,或者在组件中传入一个对象:{ vin: this.vin }

    【讨论】:

    • 就是这样,上帝保佑!
    【解决方案2】:

    我认为这里的问题是您的 vin 属性不是响应式的,因为您使用空值对其进行了初始化,但您将其更改为一个对象。试试这个:

    bindingService.fetchSomeData('xxx').then((data) => {
       Vue.set(this, 'vin', data)
    });
    

    当然,你需要import Vue from 'vue'

    【讨论】:

    • 不幸的是,我仍然遇到同样的问题,@Avocado 的灵魂有效
    【解决方案3】:

    您应该像这样将数据传递给操作:

    actions: {
        myAction( store, payload = {myCustomKey: 'my value 1'} ){
            store.commit('myCustomMutation', payload.myCustomKey);
        }
    }
    

    稍后您可以在有或没有数据的情况下调用操作:

    this.$store.dispatch('myAction');
    this.$store.dispatch('myAction', 'my value 2');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2020-06-08
      • 2020-11-03
      • 2020-10-12
      • 1970-01-01
      • 2020-05-22
      • 2020-10-05
      相关资源
      最近更新 更多