vuex-module-decorators詳解

參考:

官方文檔

vuex-module-decorators

安裝? npm install -D 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: 動態(tài)創(chuàng)建動態(tài)模塊,即new Vuex.Store({})里面不用注冊的.空著就行,

// store,當(dāng)前模塊注冊到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不然外面調(diào)用不到

? public loginInfo: User[] = [];

? // getter

? get userNumber(): number {

? ? return this.loginInfo.length;

? }

? @Mutation

? USERINFO(user: User): void {

? ? console.log(user);

? ? this.loginInfo.push(user);

? }

? // commit的兩種調(diào)用方式,第一種,Action后面的括號里面添加commit,然后return的結(jié)果就是USERINFO的參數(shù)

? @Action({ commit: 'USERINFO' })

? getZhangsan(): User {

? ? return { username: '張三', password: 'zhangsan' };

? }

? // 第二種,直接this.USERINFO調(diào)用;

? @Action

? getLisi(): void {

? ? const user = { username: '李四', password: 'lisi' };

? ? this.context.commit('USERINFO', user); // commit調(diào)用

? ? // this.USERINFO(user); // 直接調(diào)用

? }

}

// 使用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: 是動態(tài)創(chuàng)建動態(tài)模塊,所以不需要再次注冊

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); // state

? ? ? ? console.log(PassengerStoreModule.userNumber); // getter

? ? ? ? PassengerStoreModule.getZhangsan(); // actions

? ? ? ? PassengerStoreModule.getLisi(); // actions

? ? }

}

</script>

上面的案例是一個,使用了動態(tài)注冊,下面我們詳細(xì)說下,具體的使用

@Component state getter

@Mutations

@Actions

@MutationsActions

getModule

動態(tài)模塊

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 = 2

? get 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

? @Mutation

? puncture(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

? @Mutation

? addWheel(n: number) {

? ? this.wheels = this.wheels + n

? }

? @Action

? async 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中的數(shù)據(jù).在vuex-module-decorators中有MutationAction修飾器,可以直接修改state數(shù)據(jù).

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('西施');

? ? }

}

// 運(yùn)行過后,點(diǎn)擊getPassenger按鈕,用戶名和密碼會發(fā)生變化哦

getModule:創(chuàng)建類型安全的訪問

傳統(tǒng)是需要注冊到的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)

...

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內(nèi)容