vue.js - Vuex:具有动态命名空间的 createNamespacedHelpers
问题描述
在我看到的关于 vuex 模块注册的几乎所有指南、教程、帖子等中,如果模块是由组件注册的,则createNamespacedHelpers
在组件声明之前导入和定义export default
,例如:
import {createNamespacedHelpers} from 'vuex'
const {mapState} = createNamespacedHelpers('mymod')
import module from '@/store/modules/mymod'
export default {
beforeCreated() {
this.$store.registerModule('mymod', module)
}
}
这按预期工作,但是如果我们希望模块具有唯一的或用户定义的命名空间怎么办?
import {createNamespacedHelpers} from 'vuex'
import module from '@/store/modules/mymod'
export default {
props: { namespace: 'mymod' },
beforeCreated() {
const ns = this.$options.propData.namespace
this.$store.registerModule(ns, module)
const {mapState} = createNamespacedHelpers(ns)
this.$options.computed = {
...mapState(['testVar'])
}
}
}
我认为这会起作用,但它没有。
为什么需要这样的东西?因为
export default {
...
computed: {
...mapState(this.namespace, ['testVar']),
...
},
...
}
不工作
解决方案
这种通过利用 beforeCreate 来访问你想要的变量的工作方式应该可以工作,我从传递到你的组件实例的道具中做到了这一点:
import { createNamespacedHelpers } from "vuex";
import module from '@/store/modules/mymod';
export default {
name: "someComponent",
props: ['namespace'],
beforeCreate() {
let namespace = this.$options.propsData.namespace;
const { mapActions, mapState } = createNamespacedHelpers(namespace);
// register your module first
this.$store.registerModule(namespace, module);
// now that createNamespacedHelpers can use props we can now use neater mapping
this.$options.computed = {
...mapState({
name: state => state.name,
description: state => state.description
}),
// because we use spread operator above we can still add component specifics
aFunctionComputed(){ return this.name + "functions";},
anArrowComputed: () => `${this.name}arrows`,
};
// set up your method bindings via the $options variable
this.$options.methods = {
...mapActions(["initialiseModuleData"])
};
},
created() {
// call your actions passing your payloads in the first param if you need
this.initialiseModuleData({ id: 123, name: "Tom" });
}
}
我个人在要导入的模块中使用辅助函数来获取命名空间,所以如果我有我的模块存储项目并projectId
使用路由器和/或道具将 123 传递给我的组件/页面,它看起来像这样:
import projectModule from '@/store/project.module';
export default{
props['projectId'], // eg. 123
...
beforeCreate() {
// dynamic namespace built using whatever module you want:
let namespace = projectModule.buildNamespace(this.$options.propsData.projectId); // 'project:123'
// ... everything else as above
}
}
希望您觉得这个有帮助。
推荐阅读
- cordova - Cordova 插件结果未在第一次发送
- lisp - (1 2) 报错invalid function
- c - 如何设置源端口号。十进制形式
- php - 如何接收使用 guzzle 发送的 post 方法的响应
- graphql - 使用键以外的值执行获取查询
- java - 如何在不降低质量的情况下将位图转换为字节数组并返回?
- tensorflow - 在 Keras 模型中无法识别 input_shape
- c# - 不同项目模板的一般错误处理消息
- python - 尝试将包含非 ascii 字符的 csv 文件导入数据帧
- node-modules - 找不到 react-google-maps 模块:无法解析“react-google-maps/lib/places/SearchBox”