コンテンツへスキップ

createGlobalState

カテゴリ
エクスポートサイズ
125 B
最終変更日
先週
関連

Vueインスタンス間で再利用可能なように、グローバルスコープに状態を保持します。

デモ

name: 'Banana'
color: 'Yellow'
size: 'Medium'

使用方法

永続化なし(メモリ内保存)

js
import { createGlobalState } from '@vueuse/core'
// store.js
import { ref } from 'vue'

export const useGlobalState = createGlobalState(
  () => {
    const count = ref(0)
    return { count }
  }
)

より大きな例

js
import { createGlobalState } from '@vueuse/core'
// store.js
import { computed, ref } from 'vue'

export const useGlobalState = createGlobalState(
  () => {
    // state
    const count = ref(0)

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

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

    return { count, doubleCount, increment }
  }
)

永続化あり

useStorage を使用した`localStorage`への保存

js
// store.js
import { createGlobalState, useStorage } from '@vueuse/core'

export const useGlobalState = createGlobalState(
  () => useStorage('vueuse-local-storage', 'initialValue'),
)
js
// component.js
import { useGlobalState } from './store'

export default defineComponent({
  setup() {
    const state = useGlobalState()
    return { state }
  },
})

型宣言

typescript
/**
 * Keep states in the global scope to be reusable across Vue instances.
 *
 * @see https://vueuse.dokyumento.jp/createGlobalState
 * @param stateFactory A factory function to create the state
 */
export declare function createGlobalState<Fn extends AnyFn>(
  stateFactory: Fn,
): Fn

ソースコード

ソースコードデモドキュメント

コントリビューター

Anthony Fu
Anthony Fu
童欧巴
JD Solanki
Ducz01
Tobi
thefeymesaleng
plylrnsdy
wheat
Preston Alvarado
jelf

変更ログ

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2サポートの削除、バンドルの最適化、クリーンアップ (#4349)
v10.0.0-beta.0 2023/3/14
f21b2 - feat: 初期引数の受け渡しを許可 (#2790)

MITライセンスの下でリリースされています。