解决在Vuex中使用TS遇到的一些麻烦

553 阅读1分钟

在Vuex中使用TS

VueX对TS的兼容性实在是不怎么样,特别是当分多个子模块时,取子模块的state值时,经常会受到限制。如果可以的话推荐使用pinia来代替Vuex。

在Vuex中使用TS

  • store/index.ts 文件中
import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { main, IMainState } from './main

export interface IRootState {
    counter: number
}

interface IState extends IRootState {   // 这个接口是state全部的State类型,继承自根State接口
    main: IMainState                    // 如果有其他子模块,继续添加在这个接口即可
}

export const key: InjectionKey<Store<IState>> = Symbol()

export const Store = createStore<IRootState>({
    state() {
        return {
            counter: 0
        }
    },
    mutations: {},
    actions: {},
    modules: {
        main
    }
})

export function useStore() {   // 使用这个函数代替vuex中的useStore
    return baseUseStore(key)
}

  • store/main.ts 文件中
import { Module } from 'vuex'
import { IRootState } from './index.ts'

export interface IMainState {
    info: string
}

export const  main = Module<IMainState, IRootState> = {
    namespaced: true,
    state() {
        return {
            info: 'main module'
        }
    }
}

  • 根目录下 main.ts 文件中
import { createApp } from 'vue'
import App from './App.vue'
import { store, key } from './store'

const app = createApp(App)
app.use(store, key)
app.mount('#app')