在项目中加入vuex.d.ts这样会有更好的ts类型推导支持,且能避免ts报错
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
import { DemoModuleState } from 'modules/DemoModule'
declare module '@vue/runtime-core' {
interface RootState {
demoModule?: DemoModuleState
myName: string
}
interface ComponentCustomProperties {
$store: Store<RootState>
}
}
vuex的主体定义
import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { InjectionKey } from 'vue'
import demoModule from 'modules/DemoModule'
import { RootState } from '@vue/runtime-core'
export const key: InjectionKey<Store<RootState>> = Symbol()
export const store = createStore({
modules: {
demoModule
},
state: () => ({
myName: '张三'
})
})
console.log('store', store)
export function useStore() {
return baseUseStore(key)
}
模块state定义
import { ActionContext } from 'vuex'
import { RootState } from '@vue/runtime-core'
import { DO_INCREMENT, GETTER_DOUBLE_NUM, SET_COUNT } from 'store/types'
export interface DemoModuleState {
num: number
}
export default {
state: (): DemoModuleState => ({ num: 1 }),
mutations: {
[SET_COUNT](state: DemoModuleState, payload: number) {
state.num += payload
}
},
actions: {
[DO_INCREMENT](context: ActionContext<DemoModuleState, RootState>, payload: number) {
context.commit(SET_COUNT, payload)
}
},
getters: {
[GETTER_DOUBLE_NUM](state: DemoModuleState) {
return state.num * 2
}
}
}
store/types
export const SET_COUNT = 'SET_COUNT'
export const DO_INCREMENT = 'DO_INCREMENT'
export const GETTER_DOUBLE_NUM = 'GETTER_DOUBLE_NUM'