跳到主要内容

createInjectionState

分类
导出大小
386 B
上次更改
上个月

创建可注入到组件中的全局状态。

演示

  • 计数器: 0
  • 两倍: 0

用法

ts
// useCounterStore.ts
import { 
createInjectionState
} from '@vueuse/core'
import {
computed
,
shallowRef
} from 'vue'
const [
useProvideCounterStore
,
useCounterStore
] =
createInjectionState
((
initialValue
: number) => {
// state const
count
=
shallowRef
(
initialValue
)
// getters const
double
=
computed
(() =>
count
.
value
* 2)
// actions function
increment
() {
count
.
value
++
} return {
count
,
double
,
increment
}
}) export {
useProvideCounterStore
}
// If you want to hide `useCounterStore` and wrap it in default value logic or throw error logic, please don't export `useCounterStore` export {
useCounterStore
}
export function
useCounterStoreWithDefaultValue
() {
return
useCounterStore
() ?? {
count
:
shallowRef
(0),
double
:
shallowRef
(0),
increment
: () => {},
} } export function
useCounterStoreOrThrow
() {
const
counterStore
=
useCounterStore
()
if (
counterStore
== null)
throw new
Error
('Please call `useProvideCounterStore` on the appropriate parent component')
return
counterStore
}
js
// useCounterStore.ts
import { createInjectionState } from '@vueuse/core'
import { computed, shallowRef } from 'vue'
const [useProvideCounterStore, useCounterStore] = createInjectionState(
  (initialValue) => {
    // state
    const count = shallowRef(initialValue)
    // getters
    const double = computed(() => count.value * 2)
    // actions
    function increment() {
      count.value++
    }
    return { count, double, increment }
  },
)
export { useProvideCounterStore }
// If you want to hide `useCounterStore` and wrap it in default value logic or throw error logic, please don't export `useCounterStore`
export { useCounterStore }
export function useCounterStoreWithDefaultValue() {
  return (
    useCounterStore() ?? {
      count: shallowRef(0),
      double: shallowRef(0),
      increment: () => {},
    }
  )
}
export function useCounterStoreOrThrow() {
  const counterStore = useCounterStore()
  if (counterStore == null)
    throw new Error(
      'Please call `useProvideCounterStore` on the appropriate parent component',
    )
  return counterStore
}
vue
<!-- RootComponent.vue -->
<script setup lang="ts">
import { 
useProvideCounterStore
} from './useCounterStore'
useProvideCounterStore
(0)
</script> <template> <
div
>
<
slot
/>
</
div
>
</template>
vue
<!-- CountComponent.vue -->
<script setup lang="ts">
import { 
useCounterStore
} from './useCounterStore'
// use non-null assertion operator to ignore the case that store is not provided. const {
count
,
double
} =
useCounterStore
()!
// if you want to allow component to working without providing store, you can use follow code instead: // const { count, double } = useCounterStore() ?? { count: shallowRef(0), double: shallowRef(0) } // also, you can use another hook to provide default value // const { count, double } = useCounterStoreWithDefaultValue() // or throw error // const { count, double } = useCounterStoreOrThrow() </script> <template> <
ul
>
<
li
>
count: {{
count
}}
</
li
>
<
li
>
double: {{
double
}}
</
li
>
</
ul
>
</template>
vue
<!-- ButtonComponent.vue -->
<script setup lang="ts">
import { 
useCounterStore
} from './useCounterStore'
// use non-null assertion operator to ignore the case that store is not provided. const {
increment
} =
useCounterStore
()!
</script> <template> <
button
@
click
="
increment
">
+ </
button
>
</template>

提供自定义的 InjectionKey

ts
// useCounterStore.ts
import { 
createInjectionState
} from '@vueuse/core'
import {
computed
,
shallowRef
} from 'vue'
// custom injectionKey const
CounterStoreKey
= 'counter-store'
const [
useProvideCounterStore
,
useCounterStore
] =
createInjectionState
((
initialValue
: number) => {
// state const
count
=
shallowRef
(
initialValue
)
// getters const
double
=
computed
(() =>
count
.
value
* 2)
// actions function
increment
() {
count
.
value
++
} return {
count
,
double
,
increment
}
}, {
injectionKey
:
CounterStoreKey
})
js
// useCounterStore.ts
import { createInjectionState } from '@vueuse/core'
import { computed, shallowRef } from 'vue'
// custom injectionKey
const CounterStoreKey = 'counter-store'
const [useProvideCounterStore, useCounterStore] = createInjectionState(
  (initialValue) => {
    // state
    const count = shallowRef(initialValue)
    // getters
    const double = computed(() => count.value * 2)
    // actions
    function increment() {
      count.value++
    }
    return { count, double, increment }
  },
  { injectionKey: CounterStoreKey },
)

提供自定义默认值

ts
// useCounterStore.ts
import { 
createInjectionState
} from '@vueuse/core'
import {
computed
,
shallowRef
} from 'vue'
const [
useProvideCounterStore
,
useCounterStore
] =
createInjectionState
((
initialValue
: number) => {
// state const
count
=
shallowRef
(
initialValue
)
// getters const
double
=
computed
(() =>
count
.
value
* 2)
// actions function
increment
() {
count
.
value
++
} return {
count
,
double
,
increment
}
}, {
defaultValue
: 0 })
js
// useCounterStore.ts
import { createInjectionState } from '@vueuse/core'
import { computed, shallowRef } from 'vue'
const [useProvideCounterStore, useCounterStore] = createInjectionState(
  (initialValue) => {
    // state
    const count = shallowRef(initialValue)
    // getters
    const double = computed(() => count.value * 2)
    // actions
    function increment() {
      count.value++
    }
    return { count, double, increment }
  },
  { defaultValue: 0 },
)

类型声明

显示类型声明
ts
export type 
CreateInjectionStateReturn
<
Arguments
extends
Array
<any>,
Return
,
> =
Readonly
<
[ /** * Call this function in a provider component to create and provide the state. * * @param args Arguments passed to the composable * @returns The state returned by the composable */
useProvidingState
: (...
args
:
Arguments
) =>
Return
,
/** * Call this function in a consumer component to inject the state. * * @returns The injected state, or `undefined` if not provided and no default value was set. */
useInjectedState
: () =>
Return
| undefined,
] > export interface
CreateInjectionStateOptions
<
Return
> {
/** * Custom injectionKey for InjectionState */
injectionKey
?: string |
InjectionKey
<
Return
>
/** * Default value for the InjectionState */
defaultValue
?:
Return
} /** * Create global state that can be injected into components. * * @see https://vueuse.org.cn/createInjectionState * * @__NO_SIDE_EFFECTS__ */ export declare function
createInjectionState
<
Arguments
extends
Array
<any>,
Return
,
>(
composable
: (...
args
:
Arguments
) =>
Return
,
options
?:
CreateInjectionStateOptions
<
Return
>,
):
CreateInjectionStateReturn
<
Arguments
,
Return
>

来源

源文件演示文档

贡献者

Anthony Fu
ZHAO Jin-Xiang
SerKo
Anthony Fu
Arthur Darkstone
IlyaL
James Garbutt
Matvey Melishev
Hoang Do
zhangxuyang
Peter Petau
丶远方
Tanimodori

更新日志

v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
fb468 - feat: 添加 defaultValue 选项 (#3902)
v10.8.0
c2cfd - feat: injectionKey 使用可组合名称 (#3788)
v10.5.0
90d34 - feat: 添加 injectionKey 选项 (#3404)
5d948 - feat: 允许在同一组件中提供和注入 (#3387)

根据 MIT 许可证发布。