vue3中使用vuex4

vue3 中使用vuex

vuex中没有对于store中的数据进行类型定义 因此vuex中使用ts的话需要我们扩展vue的模块定义vuex的store的类型 .d.ts类型的文件就是描述性文件 在vuex中用于描述暴露出的store的类型
因为vue3 中的单文件组件setup其中没有this的概念因此想使用全局定义好的$store 则需要通过getCurrentInstance()函数获取到vue实例对象 我们还可以通过useStore()去获取格式化好的store,一般建议使用userStore()的方式去获取格式化好的store

//定义描述性文件
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  // 声明自己的 store state
  interface State {
    count: number
  }

  // 为 `this.$store` 提供类型声明
  interface ComponentCustomProperties {
    $store: Store<State>   //定义了一个
  }
}

vue3 中组合api中使用useStore

//store.ts
import{createStore,Store} from 'vuex'
import {InjectionKey} from 'vue'
///定义state的类型
export interface State{
    counter:number
}
//定义注册的key
export const key:InjectionKey<Store<State>>=Symbol()//通过泛型Store 指定key InjectionKey的泛型
//创建vuex
export const store=createStore<State>({
   state:{
       counter:1
   }
})
//main.ts
import {key,store} from './store.ts'
app.use(key,store)
//.vue 文件中
import {useStore} from 'vuex'
import {key} from 'store.ts'
//获取格式化好类型的store
const store= useStore(key)
//vue组件中使用mapState() mapGetters()
//这两个方法的使用都在组件的计算属性中
const store=useStore(key)
const count= compute(
 mapState(['state中属性的名称']).value.属性的名称.bind({$store:store})
)
const count= compute(
  mapGetters(['getters中属性的名称']).value.属性的名称.bind({$store:store}))

//使用mapAction()和mapMutations()
  const changeCount=mapMutations(['muations中的名称']).addCount.bind({$store:store})
//如果需求传递参数的时候则在调用的时候传递即可
changeCount(12) //对应的mutations中接收参数

modules使用同vue2 中定义的modules一样

后续持续整理更新

你可能感兴趣的:(vuex,javascript,vue.js,前端)