我可以为一个困难的组件创建本地 vuex 吗?
Can i create local vuex for one difficult component?
vue2 问题
我有很多具有相同结构的困难组件
PersonCard
components
PersonForm
components (many components)
index.vue
PersonImage
components (many components)
index.vue
index.vue
我想为此组件创建一个 vuex 实例,而不是全局实例。
在 index.vue 为 PersonCard 文件夹(组件的根点)创建 vuex,如果组件销毁则销毁
可能吗?
您可以在 vuex 实例中使用动态模块。这是一个 link 来阅读有关此技术的信息:vuex dynamic module
但是举例来说,假设您有一个带有管理面板的网站,并且您不需要仅在管理面板中可用的状态管理代码,因此您可以在 js 文件中创建一个 vuex 存储,例如:
// store/admin.js
export default {
namespaces: true,
modules: {},
state: () => ({}),
mutations: {},
actions: {},
getters: {},
};
然后在管理根页面或组件中导入此文件并执行以下操作:
import adminStore from '@/store/admin;
...
beforeCreate() {
const hasModule = this.$store.hasModule('admin'); // to make sure you don't register a module that already exists
if (!hasModule) this.$store.registerModule('admin', adminStore);
},
beforeDestroy() {
this.$store.unregisterModule('admin'); // removes the admin module when this component destroys
}
只要这个组件没有被破坏,你就可以使用 name spaced modules 访问所有 vuex 功能,比如:
this.$store.dispatch('admin/someActionFromAdminModule')
vue2 问题
我有很多具有相同结构的困难组件
PersonCard
components
PersonForm
components (many components)
index.vue
PersonImage
components (many components)
index.vue
index.vue
我想为此组件创建一个 vuex 实例,而不是全局实例。 在 index.vue 为 PersonCard 文件夹(组件的根点)创建 vuex,如果组件销毁则销毁
可能吗?
您可以在 vuex 实例中使用动态模块。这是一个 link 来阅读有关此技术的信息:vuex dynamic module
但是举例来说,假设您有一个带有管理面板的网站,并且您不需要仅在管理面板中可用的状态管理代码,因此您可以在 js 文件中创建一个 vuex 存储,例如:
// store/admin.js
export default {
namespaces: true,
modules: {},
state: () => ({}),
mutations: {},
actions: {},
getters: {},
};
然后在管理根页面或组件中导入此文件并执行以下操作:
import adminStore from '@/store/admin;
...
beforeCreate() {
const hasModule = this.$store.hasModule('admin'); // to make sure you don't register a module that already exists
if (!hasModule) this.$store.registerModule('admin', adminStore);
},
beforeDestroy() {
this.$store.unregisterModule('admin'); // removes the admin module when this component destroys
}
只要这个组件没有被破坏,你就可以使用 name spaced modules 访问所有 vuex 功能,比如:
this.$store.dispatch('admin/someActionFromAdminModule')