参考:
官方文档
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. 第15届全国大学生智能汽车竞赛 人工智能挑战赛(百度)
  2. 第03课:Spring Boot 启动原理
  3. 让列表只显示数据,不显示文件夹的方法
  4. C++ Primer 5th笔记(chap 17 标准库特殊设施)子表达式subexpression
  5. 简而言之,JUnit:测试隔离
  6. php 创建数据库并填充,php操作mysql--连接数据库创建表填充表
  7. 代码也能“杀”虫:此虫,真虫非Bug也
  8. 浅谈数据库设计二三事
  9. 在Tomcat 与weblogic 中的 日志(log4j) 配置系列三(log文件的存放路径)
  10. GOF业务场景的设计模式-----责任链模式
  11. 【机器学习】径向基(RBF)神经网络的tensorflow实现
  12. ASP.NET中Form验证登录后反复跳转回登录页面的问题
  13. com.alibaba.fastjson.JSONObject;的使用
  14. pcap流量中提取文件的五种方法
  15. 怎么把ppt文字大小设置一致_PPT“烫金字”,不用再劳烦设计师了
  16. 进安全模式提示”Press ENTER to continue loading SPTD.sys”
  17. 大厂对学历的要求是什么?如果学历不够,有这些补救的办法!
  18. Oracle存储空间管理
  19. ns3--TapBridge, TapNetDevice,FdNetDevice等
  20. Kubernetes 安全专家(CKS)必过心得

热门文章

  1. 《解忧杂货铺》读书笔记
  2. 初中数学最全几何模型_初中数学几何九大模型,看见的不能错过,收藏后考试必备...
  3. ASP.NET关于引用bootstrap.css导致Gridview Header无法居中
  4. html框架代码实例,HTML框架(Frames)
  5. 《惢客创业日记》2020.07.12(周日)给广告贴标签
  6. 欧拉角、旋转矩阵及四元数
  7. Python爬虫爬取一篇韩寒新浪博客
  8. 二十三种常见设计模式-简介
  9. 白话点云dgcnn中的pairwise_distance
  10. ZigBee组网(原理分析)