Javascript

ts+vuex

本文主要是介绍ts+vuex,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文件目录

|-store
      |-index.ts
      |modules
             |-home.ts
             |-about.ts

根模块,index.ts

import Vue from 'vue'
import Vuex from 'vuex'

import { IHomeState } from './modules/home'
import { IAboutState } from './modules/about'

Vue.use(Vuex)

export interface IRootState {
    home: IHomeState
    about: IAboutState
}

export default new Vuex.Store<IRootState>({})

其它模块

import { Action, getModule, VuexModule, Module, Mutation } from 'vuex-module-decorators'     //这个要装饰器单独 npm / yarn / ..下载
import store from '../index'

export interface IHomestate {
  goodsList: Array<string>
}

@Module({
  name: 'about',   //模块名字,根模块里interface IRootState的 about 就是和这里的name对应的
  dynamic: true,  //是否是动态的
  store //根模块,就是store下的index.ts
})
export default class Home extends VuexModule implements IHomestate {
  goodsList = ['fruit', 'watch', 'phone', 'book']
  get getFirstGoods(): string {
    return this.goodsList[0]
  }

  @Mutation
  changeGoodsList(goods: string): void {
    this.goodsList.push(goods)
  }

  @Action
  async syncChangeGoodsList(goods: string): Promise<boolean> {
    return new Promise((resolve) => {
      setTimeout(() => {
        this.changeGoodsList(goods)
        resolve(true)
      }, 1000)
    })
  }
}
export const HomeStore = getModule(Home)

使用,以任意vue文件为例,

login.vue 为例

import { HomeStore  } from '../store/modules/home'    //可以直接引入指定模块,而不需要引入index.ts,然后通过store.state.HomeState的方式
import { Vue, Component } from 'vue-property-decorator'
@Component
export default class Login extends Vue {
  get goodsList(): Array<string> {
    return HomeStore.goodsList
  }

  addGoods():void {
    HomeStore.changeGoodsList('cup')
  }
}
这篇关于ts+vuex的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!