Vue3 中使用 Vuex4

Vue3 中使用 Vuex4

为了符合 vue3 中 ts 的特性,我们把 vuex 仓库的数据也要进行类型管理,作用是在使用 vuex 仓库数据的时候可以看到它是什么类型

下面的代码已经实现了 ts 支持

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

// 声明仓库数据类型
export interface AllStateTypes {
    
    
    userState: number
}


// injection key
export const key: InjectionKey<Store<AllStateTypes>> = Symbol()


// 导出自定义 useStore
export function useStore() {
    
    
    return baseUseStore(key)
}


// 导出 store
export const store = createStore({
    
    
    state: {
    
    
        userState: 0
        categoryList: []
    },
    
    getters: {
    
    
        // 记得加问号不然会报错!
        book: state => state.categoryList[0]?.categoryName
    },

    // 在这里直接修改仓库的值
    mutations: {
    
    
        changeUserState(state, value) {
    
    
            state.userState = value
        }
    },
  
    // 一般异步函数放在这里
    actions: {
    
      
        incrementWait({
    
     commit, state }, parms) {
    
    
        }
    },

    // 模块化
    modules: {
    
    
    }
})
  • main.ts
// vuex
import {
    
     store, key } from './store'
app.use(store, key)
  • 组件中使用
import {
    
     useStore } from '@/store'
const store = useStore()

// 获取仓库的值
store.state.xxx
let name = computed(() => store.getters.book)

// 调用 actions
store.dispatch('incrementWait', parms)

// 调用 mutations
store.commit('increment', parms)
  • 计算属性中使用 mapState 方法也保留了,为了方便读取数据

文档:https://vuex.vuejs.org/zh/guide/state.html

computed: mapState({
    
    
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
    
    
      return state.count + this.localCount
    }
})
// 或者更简洁一点
computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

猜你喜欢

转载自blog.csdn.net/m0_63907100/article/details/129712067