gpt4 book ai didi

javascript - 视觉 : How to use component prop inside mapFields

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:42 25 4
gpt4 key购买 nike

我有通用组件和 vuex 商店。为了方便双向绑定(bind),我使用 vuex-map-fields .在组件方面,它具有 mapFields 方法,该方法创建带有突变的 get&set。我想使用 props 从 vuex 模块传递 namespace 但这似乎是不可能的。

<my-component namespace="ns1" />

// my-component code
export default {
props: ["namespace"],
computed: {
...mapFields(??this.namespace??, ["attr1", "attr2"])
}
}

当然,没有办法以这种方式使用this,所以我们无法访问 Prop 。在这种情况下,如何将命名空间指定为 prop?

最佳答案

问题(正如您可能收集到的那样)是计算属性是在 this 可用之前构造的,但是您可以通过延迟 this.namespace 的解析来解决它属性直到计算属性被调用(直到组件构建完成才会发生)。

这个概念是基于这个帖子 Generating computed properties on the fly .

基本模式是使用 get()set() 进行计算

computed: {
foo: {
get() { this.namespace...},
set() { this.namespace...},
}
}

但我们可以创建一个基于 vuex-map-fields mapFields() 函数的辅助函数(参见 here为原件)。

vuex-map-fields自带的normalizeNamespace()函数不支持我们想做的,所以我们放弃它,假设总是传入命名空间(并且store模块使用标准的 getFieldupdateField 函数)。

我改编了一个 vuex-map-fields Codesandbox 示例 here .
请注意,为方便起见,命名空间位于 data 而不是 props 中,但 props 也应该有效。

模板

<template>
<div id="app">
<div>
<label>foo </label> <input v-model="foo" /> <span> {{ foo }}</span>
</div>
<br />
<div>
<label>bar </label> <input v-model="bar" /> <span> {{ bar }}</span>
</div>
</div>
</template>

助手

<script>

const mapFields2 = (namespaceProp, fields) => {
return Object.keys(fields).reduce((prev, key) => {
const path = fields[key];
const field = {
get() {
const namespace = this[namespaceProp];
const getterPath = `${namespace}/getField`;
return this.$store.getters[getterPath](path);
},
set(value) {
const namespace = this[namespaceProp];
const mutationPath = `${namespace}/updateField`;
this.$store.commit(mutationPath, { path, value });
}
};
prev[key] = field;
return prev;
}, {});
};

export default {
name: "App",
data() {
return {
nsProp: "fooModule"
};
},
computed: {
...mapFields2("nsProp", { foo: "foo", bar: "bar" })
}
};
</script>

商店

import Vue from "vue";
import Vuex from "vuex";
import { getField, updateField } from "vuex-map-fields";
import App from "./App";

Vue.use(Vuex);
Vue.config.productionTip = false;

const store = new Vuex.Store({
modules: {
fooModule: {
namespaced: true,
state: {
foo: "initial foo value",
bar: "initail bar value"
},
getters: {
getField
},
mutations: {
updateField
}
}
}
});

new Vue({
el: "#app",
components: { App },
store,
template: "<App/>"
});

关于javascript - 视觉 : How to use component prop inside mapFields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com