vueuse中createInjectionState的使用

createInjectionState的使用

createInjectionState:创建可以注入组件的全局状态。

  • 使用
  1. 创建useCounterStore.ts
// useCounterStore.ts
import { computed, ref } from 'vue'
import { createInjectionState } from '@vueuse/shared'

const [useProvideCounterStore, useCounterStore] = createInjectionState((initialValue: number) => {
  // state
  const count = ref(initialValue)

  // getters
  const double = computed(() => count.value * 2)

  // actions
  function increment() {
    count.value++
  }

  return { count, double, increment }
})

// 如果要隐藏“useCounterStore”并将其包装在默认值逻辑中或抛出错误逻辑,请不要导出“useCounterStore”
export { useProvideCounterStore, useCounterStore }
  1. 创建Parent.vue
<script lang='ts' setup>
import { useProvideCounterStore, useCounterStore } from '@/store/useCounterStore'
useProvideCounterStore(0)
</script>

<template>
  <div class="bg-green-200">这是一个父组件</div>
  <son />
</template>

<style lang="scss" scoped></style>
  1. 创建Son.vue
<script lang='ts' setup>
import { useCounterStore } from '@/store/useCounterStore'

const { count, double, increment } = useCounterStore()!
</script>

<template>
  <div class="son bg-green-400">
    <div>这是一个子组件</div>
    <div>count:{{ count }},double:{{ double }}</div>
    <button @click="increment">changeState</button>
  </div>
</template>

<style lang="scss" scoped></style>
  1. 效果展示
    createInjectionState的效果展示
createInjectionStatecreateGlobalState的区别

在Vue.js中,createInjectionStatecreateGlobalState都是由VueUse库提供的函数,用于在组件之间共享状态。它们的区别在于作用范围和使用方式。

  1. createInjectionState:这个函数创建一个注入状态,允许在组件之间进行状态的传递。它使用Vue的provide/inject API,可以在一个父组件中创建状态,并将其注入到子组件中。子组件可以通过inject选项或inject函数来访问这个状态。这种方式适用于有层次结构的组件之间的状态传递。

  2. createGlobalState:这个函数创建一个全局状态,可以在任何组件中使用。它使用Vue的响应式系统来创建一个全局的响应式对象,所有使用这个全局状态的组件都可以共享和修改这个对象。它不需要组件之间的层次结构,可以在任何地方使用。

总结:

  • createInjectionState用于在父子组件之间传递状态,通过provide/inject API实现。
  • createGlobalState用于在任何组件中共享状态,创建一个全局响应式对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值