vuex 装饰器
cnpm install -s vuex-module-decorators
文件地址:/store/modules/about.ts
import { Module, VuexModule, Mutation, Action, getModule } from 'vuex-module-decorators'
import store from '../index'
const getList = () => {
return new Promise<Array<number>>(resolve => {
setTimeout(() => {
resolve([1, 2, 3, 4, 5, 6])
}, 500)
})
}
//暴露接口
export interface IterAboutState {
count: number;
list: Array<number>;
}
//这里配置仓库的一些基础配置
@Module({
name: "about",
dynamic: true,
store
})
export default class About extends VuexModule implements IterAboutState {
//这里是仓库所具有的一些属性
count = 1;
list = [1, 2, 3, 4];
//使用get修饰,代替了以前的getters
get filterList() {
return this.list.filter(item => item % 2 === 0)
}
get num() {
return this.count
}
//使用@mutation修饰器修饰,代替以前的mutation
@Mutation
updateCount(payload: number) {
this.count += payload
}
@Mutation
updateList(payload: Array<number>) {
this.list = payload
}
//使用@Action修饰器修饰,代替以前的Action
@Action
async getList(): Promise<boolean> {
// const res=await xxx()
//这里模拟了请求数据再给属性赋值
const res: Array<number> = await getList()
this.updateList(res)
return Promise.resolve(true)
}
}
//暴露仓库
export const AboutStore = getModule(About)
在仓库的index中暴露:/store/index.ts
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import { IterAboutState } from './modules/about'
//接受about的接口,暴露它应有的属性
interface IterRootSate {.
about: IterAboutState;
}
//暴露所有接口,暴露所有接口的属性
export default new Vuex.Store<IterRootSate>({})
页面中使用
<template>
<div class="about">
<p>{{num}}</p>
<p>{{filterList.join("-")}}</p>
<button @click="add">+1</button>
</div>
</template>
<script lang="ts">
import { Component, Vue} from "vue-property-decorator";
//这里直接导入仓库,方便了开发者的使用
import { AboutStore } from "../store/modules/about";
@Component({
name: "About",
})
export default class About extends Vue {
//这里的计算属性直接获取仓库的值
get num() {
return AboutStore.num;
}
get filterList() {
return AboutStore.filterList;
}
//使用组件方法去引用仓库的方法,比较以前的使用。方便了开发者的使用
add() {
AboutStore.updateCount(1);
}
created(){
AboutStore.getList()
}
}
</script>