vuex-module-decorators

官网

安装

npm install vuex-module-decorators
# or
yarn add vuex-module-decorators

字面意思理解就是 vuex的模块装饰器,一般结合TypeScript使用,使用这个库,可以以另一种方式编写模块。

主要功能就是用装饰器和Typescript来写vuex。好处多了类型提示

初体验

// /store/modules/foods.ts
import { VuexModule, Module, Mutation, Action } from 'vuex-module-decorators'
import get from 'axios'interface FoodEntity {name: stringweight: number,comments: string[]
}@Module
export default class Food extends VuexModule {foods: Array<FoodEntity> = []get totalFoods(): number {return this.foods.filter(food => {return food.comments && food.comments.length}).reduce((total, food) => {return total + food.comments.length}, 0)}@MutationupdateFoods(foods: FoodEntity[]): void {this.foods = foods}@Action({ commit: 'updateFoods' })async fetchFoods(): Promise<any> {return get('https://jsonplaceholder.typicode.com/comments')}
}

输出为:/store/modules/foods.ts

// /store/modules/foods.js
module.exports = {state: {foods: []},getters: {totalFoods: (state) => {return  state.foods.filter(food => {return food.comments && food.comments.length}).reduce((total, food) => {return total + food.comments.length}, 0)}},mutations: {updateFoods: (state, foods) => {state.foods = foods}},actions: {fetchFoods: async (context) => {const payload = await get('https://jsonplaceholder.typicode.com/comments')context.commit('updateFoods', payload)}}
}

简单入门

定义一个模块

如果要定义一个模块的话,先创建一个扩展自装饰器的类,VuexModule必须使用装饰器进行 Module装饰

// /store/modules/foods.ts
import { VuexModule, Module } from 'vuex-module-decorators'@module
export default class Food extends VuexModule {someField: string = 'something'
}

store中使用

store中注入 module

import Vue from 'vue'
import Vuex from 'vuex'
import Food from './modules/foods'Vue.use(Vuex)export default new Vuex.Store({state: {},mutations: {},actions: {},modules: {myFood: Food}
})

访问state

方式一:导入store

import store from '@/store'store.state.myFood.someField

方式二:在组件中使用 this.$store

this.$store.state.myFood.someField

方式三:使用 getModule()

getModule()创建类型安全的访问器

传统的模块需要先注册到 new Vuex.Storemodules中,再使用 this.$store访问。

使用 getModule()访问,TypeScript可以在编写vuex中不存在内容时自动错误提示。可以在 @Module上使用 store 模块,然后getModule(模块名);或者使用 getModule(模块名, store)的方式(这种方式暂时报错,未理解)。

// /store/modules/foods.ts
import { VuexModule, Module } from 'vuex-module-decorators'
import store from '..'@module({ dynamic:true, store, name: 'myFood' })
class MyFood extends VuexModule {someField: string = 'something'
}const Food = getModule(MyFood, store)
export default Food
// About.vue
import { Component, Vue } from "vue-property-decorator";
import Food from '../store/modules/foods'@Component
export default class About extends Vue {created(): void {console.log(Food.foods)console.log(Food.time) // Property 'time' does not exist on type 'MyFood'}
}

命名空间模块

如果想以命名空间的方式使用模块,需要在@Module装饰器中指定 namespaced: true

@Module({ namespaced: true, name: 'mm' })
class MyModule extends VuexModule {wheels = 2@MutationincrWheels(extra: number) {this.wheels += extra}get axles() {return this.wheels / 2}
}const store = new Vuex.Store({modules: {mm: MyModule}
})
// 使用
this.$store.commit('mm/incrWheels', 3)
this.$store.dispatch('mm/action')

@Module中的name值,必须要和 new Vuex.Store中的 modules中注册的名称一致;

this.$store.dispatch('action')调用需要转换为 this.$store.dispatch('na,e/action')

在命名空间模块中注册全局操作

为了能在全局范围内注册命名空间模块的操作,将参数 root: true 添加到修饰方法 @Action, @MutationAction

@Module({ namespaced: true, name: 'mm' })
class MyModule extends VuexModule {wheels = 2@MutationsetWheels(wheels: number) {this.wheels = wheels}@Action({ root: true, commit: 'setWheels' })clear() {return 0}get axles() {return this.wheels / 2}
}const store = new Vuex.Store({modules: {mm: MyModule}
})
// 使用(当全局注册一个动作后,不能被命名空间的名字调用)
this.$store.dispatch('clear')

动态模块

将特定属性传递给 @Module装饰器即可动态注册模块。需要先创建 store,然后将 store 传递给模块

// @/store/index.ts
import Vuex from 'vuex'const store = new Vuex.Store({/*...*/
})

创建动态模块

// @/store/modules/MyModule.ts
import store from '@/store'
import {Module, VuexModule} from 'vuex-module-decorators'@Module({dynamic: true, store, name: 'mm'})
export default class MyModule extends VuexModule {/*Your module definition as usual*/
}

暂不支持动态+嵌套模块

vuex-module-decorators装饰器的使用相关推荐

  1. decorators 参数_Django中decorators装饰器的使用

    1.CBV实现的登录视图 classLoginView(View):defget(self, request):"""处理GET请求""" ...

  2. Decorators TypeScript 装饰器

    Decorators 装饰器(Decorator)用来增强 JavaScript 类(class)的功能,许多面向对象的语言都有这种语法,目前有一个提案将其引入了 ECMAScript. 装饰器是一种 ...

  3. Struts和Sitemesh整合,实现多个装饰器

    2019独角兽企业重金招聘Python工程师标准>>> web.xml配置 <filter><filter-name>struts-prepare</f ...

  4. CDI services--Decorators(装饰器)

    1.Decorators装饰器综述 拦截器是一种强大的方法在应用程序捕捉运行方法和解耦.拦截器可以拦截任何java类型的调用.  这使得拦截器适合解决事务管理,安全性,以及日记记录.  本质上说,拦截 ...

  5. java 设计模式 示例_Java示例中的装饰器设计模式

    java 设计模式 示例 Decorator design pattern is used to modify the functionality of an object at runtime. A ...

  6. python 装饰器(Decorators)原理说明

    本文目的是由浅入深地介绍python装饰器原理 装饰器(Decorators)是 Python 的一个重要部分 其功能是, 在不修改原函数(类)定义代码的情况下,增加新的功能 为了理解和实现装饰器,我 ...

  7. python 装饰器分类_Python 装饰器(Decorators) 超详细分类实例

    Python装饰器分类 Python 装饰器函数: 是指装饰器本身是函数风格的实现; 函数装饰器: 是指被装饰的目标对象是函数;(目标对象); 装饰器类 : 是指装饰器本身是类风格的实现; 类装饰器 ...

  8. Javascript 装饰器极速指南

    pablo.png Decorators 是ES7中添加的JavaScript新特性.熟悉Typescript的同学应该更早的接触到这个特性,TypeScript早些时候已经支持Decorators的 ...

  9. python装饰器_Python装饰器是个什么鬼?

    不知道大家的Python入门的怎么样了啊?后面几篇Python的文章涉及一些Python中高级的内容,建议还没入门的朋友好好阅读一下如何快速入门Python赶紧上车.后台回复"python& ...

最新文章

  1. 08 线性回归 + 基础优化算法【动手学深度学习v2】
  2. deny后加to do还是doing_become to do还是doing
  3. Command ‘ifconfig‘ not found, but can be installed with: sudo apt install net-tools VM Ubuntu 解决方案
  4. python装饰器详解-python 装饰器详解
  5. 机器学习初学者入门实践:怎样轻松创造高精度分类网络
  6. CISSP考试心得分享
  7. Oracle数据库日志清理
  8. python修改pdf文件
  9. 5G关键技术之D2D
  10. 傅里叶分析 [作 者:韩 昊]
  11. onenote 插入图片或文件后 显示 您不再有权访问此笔记本。如果还原权限,我们将再次同步
  12. 骆昊python100天百度网盘_GitHub - yiailake/Python-100-Days: Python - 100天从新手到大师
  13. 10.2-控制单元CU的微程序设计
  14. c语言中读取flash值的作用,用C语言编程操作SPMC75内部Flash的方法
  15. PostgreSQL安装详细步骤(linux)
  16. 贪心算法之——摘枇杷(nyoj680)(贪心+二分搜索)
  17. html做一个qq气泡,HTML5实现QQ聊天气泡效果
  18. wps打开文件很慢很卡怎么办?
  19. 零柒歲末紀事(娛樂篇)-登高
  20. 信息学奥林匹克竞赛python_什么是USACO?来了解下美国信息学奥林匹克竞赛!

热门文章

  1. 安卓智能地图开发与实施五:在线基础底图 - ArcGIS Runtime SDK for Android(Version 100.0.0)
  2. React Native 中 TextInput 组件和中文输入冲突
  3. 嘉立创 EDA 专业版原理图绘制
  4. Linux——Linux驱动之GPIO中断的应用实战(上)(中断概述及相关函数、设备树中指定中断、驱动中获取中断)
  5. 计算机毕业生工作收入调查,大学毕业生收入调查:最高薪的工作是它
  6. 奥地利经济部长表示无需监管区块链
  7. 关于指数运算,以一有趣的应用题简单展开。
  8. 漂亮国站-亚马逊跨境电商平台新规定
  9. a卡gpuz,MSI Afterburner显卡不显示温度,启动OverdriveNTool提示atiadlxx.dll不存在的错误
  10. C#编辑、打印Excel文件不依赖Office