vuex使用ts

1,198 阅读1分钟

在项目中加入vuex.d.ts这样会有更好的ts类型推导支持,且能避免ts报错

// eslint-disable-next-line no-unused-vars
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
import { DemoModuleState } from 'modules/DemoModule'

declare module '@vue/runtime-core' {
  // 声明自己的 store state. 这个 demoModule 请与 src/store/index.ts 中的一致
  interface RootState {
    /**
     * demo模块(这个是某个module的store类型声明,这里必须要声明为可选,否则root的state的结构也会要求有这个模块字段)
     */
    demoModule?: DemoModuleState
    // 这个是root的state的某个属性类型声明
    myName: string
  }

  // 为 `this.$store` 提供类型声明
  // eslint-disable-next-line no-unused-vars
  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'

// 定义 injection key
// eslint-disable-next-line symbol-description
export const key: InjectionKey<Store<RootState>> = Symbol()
export const store = createStore({
  modules: {
    // 这个 demoModule 请保持与 src/vuex.d.ts 中的一致
    demoModule
  },
  // 这里表示的是根的state
  state: () => ({
    myName: '张三'
  })
})

console.log('store', store)

// 项目中请使用这个定义的 `useStore` 组合式函数
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'

/**
 * 当前模块的state结构定义
 */
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

/**
 * 该文件用于注册vuex中用到的所有方法名, 请保证value的唯一性
 */

export const SET_COUNT = 'SET_COUNT'
export const DO_INCREMENT = 'DO_INCREMENT'
export const GETTER_DOUBLE_NUM = 'GETTER_DOUBLE_NUM'