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<State> 指定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一样

后续持续整理更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值