createInjectionState的使用
createInjectionState:创建可以注入组件的全局状态。
- 使用
- 创建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 }
- 创建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>
- 创建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>
- 效果展示
createInjectionState
和createGlobalState
的区别
在Vue.js中,createInjectionState
和createGlobalState
都是由VueUse库提供的函数,用于在组件之间共享状态。它们的区别在于作用范围和使用方式。
-
createInjectionState
:这个函数创建一个注入状态,允许在组件之间进行状态的传递。它使用Vue的provide/inject API,可以在一个父组件中创建状态,并将其注入到子组件中。子组件可以通过inject选项或inject函数来访问这个状态。这种方式适用于有层次结构的组件之间的状态传递。 -
createGlobalState
:这个函数创建一个全局状态,可以在任何组件中使用。它使用Vue的响应式系统来创建一个全局的响应式对象,所有使用这个全局状态的组件都可以共享和修改这个对象。它不需要组件之间的层次结构,可以在任何地方使用。
总结:
createInjectionState
用于在父子组件之间传递状态,通过provide/inject API实现。createGlobalState
用于在任何组件中共享状态,创建一个全局响应式对象。