VueUse createGlobalState 创建全局状态

VueUse createGlobalState 创建全局状态,可以在跨Vue实例使用非常有用,你可以在A组件和B组件之间共享状态。典型的应用场景就是购物车,比如我们通常需要在所有的页面显示购物车内商品的数量,这时你可以使用全局状态来实现,就是简化版的pinia。

在线例子

例子

无持久化状态

创建createGlobalCartState.ts文件,会在其他组件中引用这个文件,无持久化状态可理解为F5刷新网页数就会丢失

import { computed, ref,reactive } from 'vue'
import { createGlobalState } from '@vueuse/core'

export const useGlobalCartState = createGlobalState(
  () => {
    // state 状态
    const count = ref(0);
    const food =  reactive({name:'itxst.com'})

    // getters 计算属性
    const doubleCount = computed(() => count.value * 2)

    // actions 方法
    function increment() {
      count.value++
    }
    return {food, count, doubleCount, increment }
  }
)

然后在A组件引用上面的 createGlobalCartState.ts文件,你也可以同时在其他组件导入这个文件,他们将共享一个状态

<template>
  <div>
   <p>B组件</p>
    <button @click="state.increment">点击+</button>
     <pre>状态属性:{{ state.count }}</pre>
     <pre>计算属性:{{ state.doubleCount }}</pre>
   </div>
 </template>
 <script setup lang="ts">
 /*
  tiptap 中文文档
  https://www.itxst.com/tiptap/tutorial.html
 */
 import { computed, onMounted, reactive } from 'vue';
 //导入上面创建的createGlobalCartState文件
 import {useGlobalCartState}  from './createGlobalCartState';
 
 const state=useGlobalCartState();
 onMounted(() => {
 
 }); 
 </script>

有持久化状态

有持久化状态可理解为F5刷新网页数就不会丢失,会把状态写入到本地存储里。

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

export const useGlobalState = createGlobalState(
  () => useStorage('vueuse-local-storage', {
    name: 'Banana',
    color: 'Yellow',
    size: 'Medium',
  }),
)
// component.ts 
import { useGlobalState } from './store'
export default defineComponent({
  setup() {
    const state = useGlobalState()
    return { state }
  },
})

类型声明

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