typeScript学习(六)之在vue中使用ts编写vuex

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>
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值