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')
}
}
标签:index,goodsList,ts,export,import,vuex,store 来源: https://www.cnblogs.com/Lilc20201212/p/16387019.html