Vuex+TS

时间:2021-09-16
本文章向大家介绍Vuex+TS,主要包括Vuex+TS使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

// 1. 定义数据类型
// 定义根store的数据类型
export interface IRootStateTypes {
age: number
}

  // 定义根store中的module中的数据类型
  export interface TRootWitheModule {
    // 引入login模块下的state中的数据类型
    loginModule: ILoginStateTypes

    // 如果有别的模块 可以引入其他模块的state数据类型
    // testModule: ITestStateTypes
  }

  // 导出模块的中的state类型与根state中的交叉类型
  export type IStoreType = IRootStateTypes & TRootWitheModule

// 2. 导出自定义的useStore
import { Store, useStore as useVuexStore } from "vuex"
import { IStoreType } from "./IRootStateTypes"
// 导出自定义的useStore并指出返回的数据类型
export function useStore(): Store {
return useVuexStore()
}

// 3. 其他组件内使用
// 导入自定义的useStore
import { useStore } from "@/store/index"
setup() {
const store = useStore()
const userMenus = store.state.loginModule.userMenus
return { userMenus }
}

原文地址:https://www.cnblogs.com/rzl795/p/15302323.html