useStore 是 Vuex 4(Vue.js 3 的狀態管理庫)中的一個新函數,它是組合式 API 的一部分。這個函數用於在支持組合式 API 的 Vue.js 組件中訪問 Vuex store 的實例。useStore 提供了一種在 setup 函數中獲取 store 的引用的方式,而不需要依賴 this 上下文,這在 Vue.js 3 的組合式 API 中是不可用的。
以下是 useStore 如何在 Vue.js 組件中運作的基本步驟:
導入
useStore函數:
首先,你需要從vuex包中導入useStore函數。import { useStore } from 'vuex';在組件的
setup函數中調用useStore:
在setup函數中調用useStore可以獲取到 store 的實例。setup() { const store = useStore(); // 現在你可以使用 store 中的 state、getters、mutations 和 actions return { //... }; }訪問 Vuex 狀態、提交 mutations 或派發 actions:
一旦獲取了 store 的實例,你就可以在setup函數中或其他由setup函數返回的函數中訪問 Vuex 的狀態(state)、執行 mutations 和 actions。setup() { const store = useStore(); const count = computed(() => store.state.count); function increment() { store.commit('increment'); } function asyncIncrement() { store.dispatch('asyncIncrement'); } return { count, increment, asyncIncrement, }; }
在 Vuex 中,store 是全局的,意味著它在整個應用中是單一的。這允許組件共享狀態,並保持狀態的一致性。使用 useStore 函數是在 Vue.js 3 中使用組合式 API 時訪問 Vuex store 的標準方式。這種方法將 Vuex 的集中式狀態管理與 Vue.js 3 的組合式 API 相結合,使得代碼更加模組化和可測試。

![[SQL] Update Where 依照條件更新指定欄位](https://static.coderbridge.com/images/covers/default-post-cover-2.jpg)
