百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
V

vuex-class-modules

> 编程语言
开源

TypeScript 类的装饰器用于 vuex 模块

192 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

TypeScript 类的装饰器用于 vuex 模块

vuex-class-modules

This is yet another package to introduce a simple type-safe class style syntax for your vuex modules, inspired by vue-class-component.

Installation

npm install vuex-class-modules

And make sure to have the --experimentalDecorators flag enabled.

Both a commonjs and a esm module build are published. If you have a webpack-based setup, it will use the esm modules by default.

Usage

Vuex modules can be written using decorators as a class:

…

The module will automatically be registered to the store as a namespaced dynamic module when it is instantiated. (The modules are namespaced to avoid name conflicts between modules for getters/mutations/actions.)

The module can then be used in vue components as follows:

typescript
// MyComponent.vue
import Vue from "vue";
import { userModule } from "path/to/user-module.ts";

export class MyComponent extends Vue {
  get firstName() {
    return userModule.firstName; // -> store.state.user.firstName
  }
  get fullName() {
    return userModule.fullName; // -> store.getters["user/fullName]
  }

  created() {
    userModule.setFirstName("Foo"); // -> store.commit("user/setFirstName", "Foo")
    userModule.loadUser(); // -> store.dispatch("user/loadUser")
  }
}

What about rootState and rootGetters?

There are two ways to access other modules within a module, or dispatch actions to other modules.

  1. Simply import the instantiated module (suitable if the modules are instantiated in the same file as they are defined):
typescript
// my-module.ts

// import the module instance
import { otherModule } from "./other-module";

@Module
class MyModule extends VuexModule {
  get myGetter() {
    return otherModule.foo;
  }

  @Action
  async myAction() {
    await otherModule.someAction();
    // ...
  }
}
  1. The other module can be registered through the constructor (suitable if the modules are instantiated elsewhere)
…

The local modules will not be part of the state and cannot be accessed from the outside, so they should always be declared private.

typescript
myModule.otherModule; // -> undefined

The store.watch function

Vuex can also be used ouside of vue modules. To listen for changes to the state, vuex provides a watch method.

This api is also provided by vuex-class-modules under the method name $watch to prevent name collisions. For example you can do:

typescript
import store from "./store";
import { MyModule } from "./my-module";

const myModule = new MyModule({ store, name: "MyModule" });
myModule.$watch(
  (theModule) => theModule.fullName,
  (newName: string, oldName: string) => {
    // ...
  },
  {
    deep: false,
    immediate: false,
  }
);

and to unwatch:

typescript
const unwatch = myModule.$watch(...);
unwatch();

Register options

  • name [required]: Name of the module
  • store [required]: The vuex store - which can just be instantiated as empty:
typescript
// store.ts
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({});

Module options

The module decorator can also accept options:

  • generateMutationSetters [optional, default=false]: Whether automatic mutation setters for the state properties should be generated, see Generate Mutation Setters.

Example

The vuex shopping cart example rewritten using vue-class-component and vuex-class-modules can be found in the example directory. Build the example using:

npm run example

Caveats of this

As for vue-class-component this inside the module is just a proxy object to the store. It can therefore only access what the corresponding vuex module function would be able to access:

…

Local Functions

The module can have non-mutation/action functions which can be used inside the module. As for local modules, these functions will not be exposed outside the module and should therefore be private. this will be passed on to the local function from the getter/mutation/action.

typescript
@Module
class MyModule extends VuexModule {
  get myGetter() {
    return myGetterHelper();
  }
  private myGetterHelper() {
    // same 'this' context as myGetter
  }

  @Mutation
  myMutation() {
    this.myMutationHelper();
  }

  // should be private
  myMutationHelper() { /* ... */}
}
const myModule = new MyModule({ store, name: "myModule });
myModule.myMutationHelper // -> undefined.

Generate Mutation Setters

As I often find myself writing a lot of simple setter mutations like

typescript
@Module
class UserModule extends VuexModule {
  firstName = "Foo";
  lastName = "Bar";

  @Mutation
  setFirstName(firstName: string) {
    this.firstName = firstName;
  }
  @Mutation
  setLastName(lastName: string) {
    this.lastName = lastName;
  }
}

a module option generateMutationSetters has been added, which when enabled will generate a setter mutation for each state property. The state can then be modified directly from the actions:

typescript
@Module({ generateMutationSetters: true })
class UserModule extends VuexModule {
  firstName = "Foo";
  lastName = "Bar";

  // Auto generated:
  // @Mutation set__firstName(val: any) { this.firstName = val }
  // @Mutation set__lastName(val: any) { this.lastName = val }

  @Action
  async loadUser() {
    const user = await fetchUser();
    this.firstName = user.firstName; // -> this.set__firstName(user.firstName);
    this.lastName = user.lastName; // -> this.set__lastName(user.lastName);
  }
}

NOTE: Setters are only generated for root-level state properties, so in order to update a property of an object you have to use a mutation or replace the entire object:

typescript
@Module({ generateMutationSetters: true })
class UserModule extends VuexModule {
  user = {
    id: 123,
    name: "Foo",
  };

  @Mutation
  setUserName() {
    this.user.name = "Bar"; // OK!
  }

  @Action
  async loadUser() {
    this.user.name = "Bar"; // Bad, the state is mutated outside a mutation
    this.user = { ...this.user, name: "Bar" }; // OK!
  }
}

Vite HMR

Vite (and possibly other bundlers) uses import.meta.hot for HMR, which vuex-class-modules doesn't support currently. Instead a static property

typescript
VuexModule.__useHotUpdate = true; // default false

is provided, which will force hot updates to the store instead of throwing an error when a module with a duplicate name is registered. This could for instance be set only in dev mode

typescript
VuexModule.__useHotUpdate = import.meta.env.DEV;

License

MIT

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言