【问题标题】:Vuex-map-fields updating multiple stores through modulesVuex-map-fields 通过模块更新多个 store
【发布时间】:2018-10-09 05:46:38
【问题描述】:

我正在使用 Vuex 模块来陈述我的数据。 我将数据存储在多个模块中,以保持我的代码库整洁。

在使用 vuex-map-fields 时,我遇到了使用来自多个模块的数据的情况。 似乎没有办法做到这一点,或者我做错了。

以下是我当前的代码; 我的组件

<template>
    <div class="">
        <input type="text" v-model="no_panels"><br>
        <input type="text" v-model="firstName"><br>
        <router-link to="/step-2">Go to step 2</router-link>
    </div>
</template>

<script>
import { createHelpers } from 'vuex-map-fields';

const { mapFields } = createHelpers({
    getterType: [
        'getKitchenField',
        'getApplicantField',
    ],
    mutationType: 'updateKitchenField',
});

export default {
    computed: {
        ...mapFields(['no_panels', 'firstName', 'lastName'])
    },
}
</script>

我的商店文件

import kitchen from './kitchen';
import applicant from "./applicant";

export default {
    modules: {
        kitchen: kitchen,
        applicant: applicant
    },
    strict: false
 }

申请者.js

import { createHelpers } from 'vuex-map-fields';

const { getApplicantField, updateApplicantField } = createHelpers({
    getterType: 'getApplicantField',
    mutationType: 'updateApplicantField',
});

export default {
    state: {
         firstName: '',
        lastName: ''
    },
    getters: {
        getApplicantField
    },
    mutations: {
        updateApplicantField
    }
}

上面的代码导致如下错误:

渲染错误:“TypeError: this.$store.getters[getterType] is not a function”

【问题讨论】:

  • 不太清楚你的问题是什么,你试过在你的子模块声明中使用namespaced: true吗?
  • 对不起,我会用错误是什么来修改问题。
  • 当使用命名空间模块时,您需要使用模块名称和斜杠来引用它,即'kitchen/getKitchenField''applicant/getApplicantField'

标签: vue.js vuejs2 vue-component vuex vuex-modules


【解决方案1】:

我是vuex-map-fields的创造者,作者问the same question on GitHub

您可以解构并重命名createHelpers() 的返回值并调用它两次,而不是将多个getter 传递给createHelpers()

const { mapFields: mapKitchenFields } = createHelpers({
  getterType: 'getKitchenField',
  mutationType: 'updateKitchenField',
});
const { mapFields: mapApplicantFields } = createHelpers({
  getterType: 'getApplicantField',
  mutationType: 'updateApplicantField',
});

export default {
  computed: {
    ...mapKitchenFields(['no_panels']),
    ...mapApplicantFields(['firstName', 'lastName']),
  },
}

如果解构语法对您来说是新的,您可以从 Wes Bos 那里了解更多信息:https://wesbos.com/destructuring-renaming/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-14
    • 2018-09-15
    • 1970-01-01
    • 2022-01-19
    • 2021-08-27
    • 2021-11-22
    • 2020-06-24
    • 2021-03-18
    相关资源
    最近更新 更多