参考:
官方文档
vuex-module-decorators

安装  npm install  vuex-module-decorators

安装成功后就可以使用啦,先看一个完整案例

// store/modules/passenger.ts
import {Module,VuexModule,Mutation,Action,getModule,} from 'vuex-module-decorators';
import store from '@/store';type User = { username: string; password: string; }// dynamic: true: 动态创建动态模块,即new Vuex.Store({})里面不用注册的.空着就行,
// store,当前模块注册到store上.也可以写在getModule上,即getModule(PassengerStore,store)
// namespaced: true, name: 'passenger' 命名空间
@Module({name: 'passenger', dynamic: true, namespaced: true, store,
})
export default class PassengerStore extends VuexModule {// state => 要public不然外面调用不到public loginInfo: User[] = [];// getterget userNumber(): number {return this.loginInfo.length;}@MutationUSERINFO(user: User): void {console.log(user);this.loginInfo.push(user);}// commit的两种调用方式,第一种,Action后面的括号里面添加commit,然后return的结果就是USERINFO的参数@Action({ commit: 'USERINFO' })getZhangsan(): User {return { username: '张三', password: 'zhangsan' };}// 第二种,直接this.USERINFO调用;@ActiongetLisi(): void {const user = { username: '李四', password: 'lisi' };this.context.commit('USERINFO', user); // commit调用// this.USERINFO(user); // 直接调用}
}
// 使用getModule: 对类型安全的访问
export const PassengerStoreModule = getModule(PassengerStore);// sotre/index.ts
import Vue from 'vue';
import Vuex from 'vuex';Vue.use(Vuex);
export default new Vuex.Store({ }); // 由于passenger->dynamic: true: 是动态创建动态模块,所以不需要再次注册

index.vue页面使用

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { PassengerStoreModule } from '@/store/modules/passenger';@Component
export default class IndexPage extends Vue {created() {console.log(PassengerStoreModule.loginInfo); // stateconsole.log(PassengerStoreModule.userNumber); // getterPassengerStoreModule.getZhangsan(); // actionsPassengerStoreModule.getLisi(); // actions}
}
</script>

上面的案例是一个,使用了动态注册,下面我们详细说下,具体的使用
@Component state getter

@Mutations

@Actions

@MutationsActions

getModule

动态模块

state:

import { Module, VuexModule } from 'vuex-module-decorators'@Module
export default class Vehicle extends VuexModule {wheels = 2
}等同于下面的代码export default {state: { wheels: 2 }
}

getter

import { Module, VuexModule } from 'vuex-module-decorators'@Module
export default class Vehicle extends VuexModule {wheels = 2get axles() {return this.wheels / 2}
}等同于下面的代码export default {state: { wheels: 2 },getters: {axles: (state) => state.wheels / 2}
}

@Mutations

import { Module, VuexModule, Mutation } from 'vuex-module-decorators'@Module
export default class Vehicle extends VuexModule {wheels = 2@Mutationpuncture(n: number) {this.wheels = this.wheels - n}
}等同于下面的代码export default {state: { wheels: 2 },mutations: {puncture: (state, payload) => {state.wheels = state.wheels - payload}}
}

@Actions

import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'
import { get } from 'request'@Module
export default class Vehicle extends VuexModule {wheels = 2@MutationaddWheel(n: number) {this.wheels = this.wheels + n}@Actionasync fetchNewWheels(wheelStore: string) {const wheels = await get(wheelStore)this.context.commit('addWheel', wheels)}
}等同于下面的代码const request = require('request')
export default {state: { wheels: 2 },mutations: {addWheel: (state, payload) => {state.wheels = state.wheels + payload}},actions: {fetchNewWheels: async (context, payload) => {const wheels = await request.get(payload)context.commit('addWheel', wheels)}}
}

@MutationAction

在vuex中是要通过commit来更改state中的数据.在vuex-module-decorators中有MutationAction修饰器,可以直接修改state数据.

export default class PassengerStore extends VuexModule {public username = '';public password = '';//'username'和'password'被返回的对象替换,//格式必须为`{username:...,password:...}` @MutationAction({ mutate: ['username', 'password'] })async setPassenger(name: string) {const response: any = await request(name); // 接口返回 [{name:'张三',password:'123456'}]// 此处返回值必须和上面mutate后面的名称保持一致;return {username: response[0].name,password: response[0].password,};}
}// index.vue中使用
<template><div class="">用户名:{{PassengerStoreModule.username}}<br/>密码:{{PassengerStoreModule.password}}<br/><button @click="getPassenger()">getPassenger</button></div>
</template>...
@Component
export default class IndexPage extends Vue {private PassengerStoreModule: any = PassengerStoreModule;getPassenger() {PassengerStoreModule.setPassenger('西施');}
}// 运行过后,点击getPassenger按钮,用户名和密码会发生变化哦

getModule:创建类型安全的访问

传统是需要注册到的new Vuex.Store上,然后通过this$store访问,使用getModule访问类型更加安全,
可以再module上使用store模块,然后getModule(模块名)
也可以getModule(模块名,this.$store)的形式

import { Module, VuexModule, getModule } from 'vuex-module-decorators'
import store from '@/store'// 1. module上使用store
@Module({ dynamic: true, store, name: 'mymod' })
class MyModule extends VuexModule {someField: number = 10
}
const myMod = getModule(MyModule)
myMod.someField //works
myMod.someOtherField //Typescript will error, as field doesn't exist// 2. module上不使用store,  getModule使用store
@Module({ dynamic: true, name: 'mymod' })
class MyModule extends VuexModule {someField: number = 10
}
const myMod = getModule(MyModule,store)
...

动态模块

动态模块:使用getModule获取数据,页面调用的时候,store.state里面才会显示改模块的信息
非动态模块:页面初始的时候,手动添加到new Vuex.Store({ modules: {  user: PassengerStore } }),页面刷新state里面可以直接看到当前模块的变量以及方法。

我们将上面的passenger.ts改写才非动态模块

import {Module,VuexModule,Mutation,Action,getModule,} from 'vuex-module-decorators';
// import store from '@/store'; // 去掉storetype User = { username: string; password: string; }@Module({name: 'user', namespaced: true,})
export default class PassengerStore extends VuexModule {// ...同上方案例一模一样
}// 因为getModule是要对应store的.上面去掉了store,所以也要去掉 getModule,
// export const PassengerStoreModule = getModule(PassengerStore); // store/index.ts
import Vue from 'vue';
import Vuex from 'vuex';
import PassengerStore from './modules/passenger';Vue.use(Vuex);
export default new Vuex.Store({modules: {user: PassengerStore},
});//index.vue 使用
import PassengerStore from '@/store/modules/passenger';
import { getModule } from 'vuex-module-decorators';...
created() {const PassengerStoreModule = getModule(PassengerStore, this.$store);console.log(PassengerStoreModule.loginInfo);PassengerStoreModule.getZhangsan();PassengerStoreModule.getLisi();console.log(PassengerStoreModule.userNumber);}
...

再试运行,发现跟之前的结果没差别.

命名空间

const moduleA1 = {namespaced: true,...
};
const moduleA = {namespaced: true,modules: {a1: moduleA1,},
};
const moduleB = {// no namespaced...};
export default new Vuex.Store({...modules: {a: moduleA,b: moduleB,},
});

上面的例子,store包含了两个模块,a和b,a模块里面包含了a1,
打个比方a,a1和b的actions里面分别有个getMsgA(),getMsgB(),getMsgA1()方法,
在页面上用this.$store.dispatch调用这些方法.
a和a1都有命名空间,所以
this.$store.dispatch('a/getMsgA');
this.$store.dispatch('a/a1/getMsgA1');
由于b没有命名空间,所以this.$store.dispatch('b/getMsgB');是会报错的.

那么如果再a1里面如果查看root的state呢,vux提供了rootState, rootGetters.

actions: {someAction ({ dispatch, commit, getters, rootGetters }) {getters.someGetter // -> 'a/someGetter'rootGetters.someGetter // -> 'someGetter'dispatch('someOtherAction') // -> 'a/someOtherAction'dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'commit('someMutation') // -> 'a/someMutation'commit('someMutation', null, { root: true }) // -> 'someMutation'}

demo地址:https://github.com/slailcp/vue-cli3/blob/master/src/pc-project/store/modules/login.ts

vuex-module-decorators详解相关推荐

  1. 【ES6】Module模块详解

    [ES6]Module模块详解 一.Module的由来 二.严格模式 三.export命令 四.import命令 查看更多ES6教学文章: 参考文献 引言:由于两个JS文件之间相互使用必须通过一个ht ...

  2. pytorch教程之nn.Module类详解——使用Module类来自定义网络层

    前言:前面介绍了如何自定义一个模型--通过继承nn.Module类来实现,在__init__构造函数中申明各个层的定义,在forward中实现层之间的连接关系,实际上就是前向传播的过程. 事实上,在p ...

  3. pytorch教程之nn.Module类详解——使用Module类来自定义模型

    pytorch教程之nn.Module类详解--使用Module类来自定义模型_MIss-Y的博客-CSDN博客_nn是什么意思前言:pytorch中对于一般的序列模型,直接使用torch.nn.Se ...

  4. ES Module原理详解

    ES Module原理详解 一.ES Modules如何工作 流程简析 二.模块加载 1.构造 2.实例化 3.求值 总结 参考 ES Module 系列: ES Module使用详解 ES Modu ...

  5. Angular目录结构分析以及app.module.ts详解

    场景 Angular介绍.安装Angular Cli.创建Angular项目入门教程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detail ...

  6. Vue进阶(四十三):Vuex之Mutations详解

    文章目录 一.前言 二.如何使用 mutations ? 三.源码分析 四.拓展阅读 一.前言 通俗理解mutations,里面装着一些改变数据方法的集合,这是Vuex设计很重要的一点,就是把处理数据 ...

  7. vuex结合php,Vuex模块化(module)实例详解

    本文主要和大家介绍Vuex 模块化(module),小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助到大家. 一.为什么需要模块化 前面我们讲到的例子都在一个状态树里进行,当一个项目比较 ...

  8. Lua中的模块与module函数详解

    很快就要开始介绍Lua里的"面向对象"了,在此之前,我们先来了解一下Lua的模块. 1.编写一个简单的模块 Lua的模块是什么东西呢?通常我们可以理解为是一个table,这个tab ...

  9. C++20四大之一:module特性详解

    前言 C++20最大的特性是什么? --最大的特性是迄今为止没有哪一款编译器完全实现了所有特性. C++20标准早已封版,各大编译器也都已支持了C++20中的多数特性,但迄今为止(2021.7),尚未 ...

  10. 技术干货 | C++20 四大特性之一:Module 特性详解

    导读:C++20 标准早已封版,各大编译器也都已支持了 C++20 中的多数特性,但迄今为止(2021.7),尚未有哪一款编译器完整支持 C++20 中的所有特性.本文仅介绍 C++20 四大特性当中 ...

最新文章

  1. Java项目:嘟嘟校园一卡通系统(java+JSP+Servlet+html+css+JavaScript+JQuery+Ajax+mysql)
  2. rancher安装mysql_四、rancher搭建Mysql集群化部署,做到同步备份
  3. Jackson 注解 -- 指定输出顺序
  4. 自动化交易综述——互联网金融
  5. Erlang与java的内存架构比较
  6. vcode tsconfig.json 无故报错 -- 找不到任何输入
  7. LeetCode 360. 有序转化数组(抛物线对称轴)
  8. Linux的实际操作:给Linux添加一块新硬盘
  9. HTML5 Video DOM 入门体验
  10. 【华为云分享】机器学习笔记(七) ---- 贝叶斯分类
  11. 多实例linux自动启动,Linux 下自动启动多个oracle实例
  12. 软件测试--04测试用例/测试方法
  13. 【渝粤题库】陕西师范大学164105 物流管理学 作业(高起专)
  14. 如何对西数硬盘固件进行逆向分析(下)
  15. pmp考试有题库么?有多少题?
  16. 智慧运维:基于 BIM 技术的可视化管理系统
  17. Python头歌合集(题集附解)
  18. 【javaIO流】--->IO流解析
  19. Latex 制作表格
  20. Javaweb新手软件推荐

热门文章

  1. JavaScript权威指南
  2. c语言定时器作用,定时器简单运用
  3. 纪念SlingShot
  4. 停车场自动停车,取车创意
  5. 软件开发的22条黄金法则
  6. 保研日记--中国人民大学信息学院(人大信院)
  7. 客户端证书与服务器证书有什么区别?
  8. 社会学和游戏制作的关系。
  9. 微软又给谷歌「双重暴击」,ChatGPT或将加入Word、PPT和Excel!
  10. Java学习之旅(十三):循环控制之 continue 语句