跳到主要內容

createInjectionState

類別
匯出大小
364 B
上次變更
4 個月前

建立可注入到組件中的全域狀態。

範例

  • 計數:0
  • 雙倍:0

用法

ts
import { createInjectionState } from '@vueuse/core'
// useCounterStore.ts
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
import { createInjectionState } from '@vueuse/core'
// useCounterStore.ts
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
import { createInjectionState } from '@vueuse/core'
// useCounterStore.ts
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
import { createInjectionState } from '@vueuse/core'
// useCounterStore.ts
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
import { createInjectionState } from '@vueuse/core'
// useCounterStore.ts
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
import { createInjectionState } from '@vueuse/core'
// useCounterStore.ts
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 },
)

類型宣告

typescript
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.dev.org.tw/createInjectionState
 *
 */
export declare function createInjectionState<
  Arguments extends Array<any>,
  Return,
>(
  composable: (...args: Arguments) => Return,
  options?: CreateInjectionStateOptions<Return>,
): readonly [
  useProvidingState: (...args: Arguments) => Return,
  useInjectedState: () => Return | undefined,
]

原始碼

原始碼範例文件

貢獻者

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

變更日誌

v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundle 並清理 (#4349)
v10.10.0 於 2024/5/27
fb468 - feat: 新增 defaultValue 選項 (#3902)
v10.8.0 於 2024/2/20
c2cfd - feat: injectionKey 使用 composable 名稱 (#3788)
v10.5.0 於 2023/10/7
90d34 - feat: 新增 injectionKey 選項 (#3404)
5d948 - feat: 允許在同一個組件中 provide 和 inject (#3387)

根據 MIT 許可證發布。