【问题标题】:How to populate form from store state data returned from vuex with getters?如何使用 getter 从 vuex 返回的存储状态数据填充表单?
【发布时间】:2019-11-10 18:30:01
【问题描述】:

我尝试使用相同的表单进行创建和编辑。我已经将带有道具的 id 从一个组件传递到另一个组件,它工作正常。使用该 ID,我尝试在 getter 的帮助下从 vuex 存储状态中获取数据。吸气剂正确地返回了数据。但我无法填写表格。我已经尝试过创建、计算和挂载属性,但我不起作用。

我尝试使用 mount、create 和 computed 填充表单。

我希望当我单击编辑按钮时会填充表单的输出,但在表单中看不到任何内容。

模板代码

<template>
    <b-form-group
    label-cols="12"          
    label="Minimum Salary: "
    >
        <b-form-input
              id="input-1"
              v-model="record.min_salary"
              type="number"
            ></b-form-input>
    </b-form-group>

          <b-form-group
            label-cols="12"
            label-cols-lg="3"
            label-for="input-2"
            label="Maximum Salary: "
            label-align-sm="right"
            label-align="left"
          >
            <b-form-input
              id="input-2"
              v-model="record.max_salary"
              type="number"
            ></b-form-input>
          </b-form-group>

          <b-form-group
            label-cols="12"
            label-cols-lg="3"
            label-for="input-2"
            label="Tax Rate: "
            label-align-sm="right"
            label-align="left"
          >
            <b-form-input
              id="input-2"
              v-model="record.tax_rate"
              type="number"
            ></b-form-input>
          </b-form-group>
          <b-form-group
            label-cols="12"
            label-cols-lg="3"
            label-for="input-2"
            label="Deductible: "
            label-align-sm="right"
            label-align="left"
          >
            <b-form-input
              id="input-2"
              v-model="record.deductible"
              type="number"
            ></b-form-input>
          </b-form-group>
          </b-form>
    </template>

Vue 脚本代码

<script>
    import { mapGetters, mapActions } from "vuex";
    export default {
      props: ["id"],
      data: () => ({
      update: false,
        record: {
          min_salary: "",
          max_salary: "",
          tax_rate: "",
          deductible: ""
       }
      }),

      created() {
        if (this.id != null) {
          this.update = true;
          this.fetchIncomeTaxRate(this.id);
          this.createoredit = "EDIT";
        }
      },
      mounted() {
         if (this.id != null) {
          this.record.min_salary = this.getIncomeTaxRate.min_salary;
          this.record.max_salary = this.getIncomeTaxRate.max_salary;
          this.record.tax_rate = this.getIncomeTaxRate.tax_rate;
          this.record.deductible = this.getIncomeTaxRate.deductible;
       }
      },
      methods: { ...mapActions(["fetchIncomeTaxRate"])},
      computed: {...mapGetters(["getIncomeTaxRate"])}
     };
</script>

商店代码

import axios from "axios";
import commonAPI from "../commonAPI";

const state = {
  incomeTaxRate: []
};

const mutations = {

  setIncomeTaxRate: (state, incomeTaxRate) =>
    (state.incomeTaxRate = incomeTaxRate)
};

const getters = {
  getIncomeTaxRate: state => {
    return state.incomeTaxRate;
  }
};

const actions = {
  async fetchIncomeTaxRate({ commit }, id) {
    const response = await axios.get(
      commonAPI.PAYROLL_BASE_URL + `/income-tax-rates/${id}`
    );
    commit("setIncomeTaxRate", response.data);
  }
};

export default {
  state,
  mutations,
  getters,
  actions
};

【问题讨论】:

    标签: vue.js vuex vue-router


    【解决方案1】:

    在不查看商店代码的情况下给出具体答案有点困难,但您必须等到商店完成获取数据后才能尝试将其读入您的表单。

    可能最简单的方法是使用 fetchIncomeTaxRate 返回的 Promise。所有actions 在调用时都会返回一个 Promise,即使您自己没有返回一个。确保您返回了一个合适的 Promise,即在加载数据之前不会解析的 Promise。如果您使用支持 Promises 的库(如 axios)加载数据,那么这应该非常简单,您只需返回它返回给您的 Promise。

    一旦你返回了一个合适的 Promise,你就可以这样做:

    this.fetchIncomeTaxRate(this.id).then(() => {
        this.record.min_salary = this.getIncomeTaxRate.min_salary;
        // ... others here
    });
    

    您可能需要添加额外的代码,以防止在填充相关数据之前看到/编辑表单。

    使用 Promises 的替代方法是使用 watch 等待 getIncomeTaxRate 更改。但是,很难确保您只对正确的更改做出反应。

    更新:

    既然您已经发布了您的商店代码,我已经尝试自己运行您的代码(尽可能接近)并且如果我按照上面概述的方式使用 thenrecord 更新得很好。这很可能表明您发布的代码中没有另一个问题。例如,从服务器返回的数据可能与您期望的格式不完全一致。

    为了进一步诊断,我建议放入一些控制台日志记录。对于初学者,我会在then 的顶部添加一些内容:

    this.fetchIncomeTaxRate(this.id).then(() => {
        console.log('in then', this.getIncomeTaxRate, this.getIncomeTaxRate.min_salary);
    
        this.record.min_salary = this.getIncomeTaxRate.min_salary;
        // ... others here
    });
    

    我也会在fetchIncomeTaxRate 中添加一些:

    async fetchIncomeTaxRate({ commit }, id) {
      console.log('called fetchIncomeTaxRate');
    
      const response = await axios.get(
        commonAPI.PAYROLL_BASE_URL + `/income-tax-rates/${id}`
      );
      commit("setIncomeTaxRate", response.data);
    
      console.log('committed', response.data);
    }
    

    不仅记录的值应该正确,而且日志消息的顺序也很重要。数据应在调用then 之前提交。

    【讨论】:

    • @TesfuTekleab 请将该代码添加到您的问题中,我会更新我的答案。
    • 我已经用 vuex 商店代码更新了我的问题。感谢您的帮助。
    • @TesfuTekleab 我已经更新了我的答案,提供了一些进一步调试的建议,但我原来的解决方案对我来说似乎仍然正确。
    • 感谢它现在工作正常。错误不在我的代码中,而是来自后端。
    猜你喜欢
    • 2019-08-17
    • 2019-10-09
    • 2021-08-23
    • 2018-12-16
    • 1970-01-01
    • 2021-09-30
    • 2020-07-03
    • 1970-01-01
    • 2020-01-01
    相关资源
    最近更新 更多