Vue3中的createGlobalState用法及示例詳解
1. 基本知識
createGlobalState 是 Vue 3 中一種管理全局狀態(tài)的簡便方式,通常用于管理多個組件間共享的狀態(tài)
由 @vueuse/core 提供的,允許創(chuàng)建一個響應式的全局狀態(tài),可以在任意組件中訪問和更新
基本的特性如下:
- 響應式:狀態(tài)是響應式的,任何組件對狀態(tài)的訪問和修改都會觸發(fā)相應的更新
- 簡單易用:通過簡單的 API 可以創(chuàng)建和管理全局狀態(tài)
- 模塊化:可以根據需要將狀態(tài)邏輯分離到不同的模塊中
特性 | 有 createGlobalState | 沒有 createGlobalState |
---|---|---|
全局狀態(tài)管理 | 方便、簡單 | 復雜,通常需要手動管理狀態(tài)傳遞 |
響應式 | 自動響應式更新 | 需要使用 Vuex 或 EventBus 等手動實現 |
代碼可讀性 | 更清晰、更簡潔 | 代碼可能更加混亂 |
模塊化 | 可以方便地組織全局狀態(tài) | 通常需要復雜的狀態(tài)管理邏輯 |
需要確保安裝了 @vueuse/core:
2. Demo
一般與 useStorage 一起存儲在 localStorage 中比較好,否則刷新網頁鏈接的時候會丟失的!
以下是沒有存儲到localStorage的Demo
相關的Demo如下:
src/globalState.js,定義全局狀態(tài):
// src/globalState.js import { createGlobalState } from '@vueuse/core'; import { reactive } from 'vue'; // 創(chuàng)建全局狀態(tài) export const useGlobalState = createGlobalState(() => { return reactive({ count: 0 }); });
MyDemoComponent.vue 中使用全局狀態(tài):
<template> <div> <h2>全局計數器</h2> <p>當前計數: {{ globalState.count }}</p> <button @click="increment">增加計數</button> </div> </template> <script> import { useGlobalState } from '../globalState'; export default { setup() { const globalState = useGlobalState(); const increment = () => { globalState.count++; }; return { globalState, increment }; } }; </script>
確保在 App.vue 中使用新的組件:
<template> <div id="app"> <MyDemoComponent /> </div> </template> <script> import MyDemoComponent from './components/MyDemoComponent.vue'; export default { components: { MyDemoComponent } }; </script>
最終截圖如下:
也給一版沒有使用的Demo:
可能會使用一個簡單的 EventBus 或 Vuex 來管理全局狀態(tài),示例可能如下:
// src/eventBus.js import { reactive } from 'vue'; import { createApp } from 'vue'; const state = reactive({ count: 0 }); const eventBus = createApp({}); export const useEventBus = () => { return { state, increment: () => { state.count++; eventBus.config.globalProperties.$emit('update'); } }; };
在 MyDemoComponent.vue 中:
<template> <div> <h2>全局計數器</h2> <p>當前計數: {{ eventBus.state.count }}</p> <button @click="increment">增加計數</button> </div> </template> <script> import { useEventBus } from '../eventBus'; export default { setup() { const eventBus = useEventBus(); return { eventBus, increment: eventBus.increment }; } }; </script>
到此這篇關于Vue3中的createGlobalState用法及示例詳解的文章就介紹到這了,更多相關Vue3 createGlobalState用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue2.5.2使用http請求獲取靜態(tài)json數據的實例代碼
這篇文章主要介紹了vue2.5.2使用http請求獲取靜態(tài)json數據的實例代碼,需要的朋友可以參考下2018-02-02