:::
10. Vuex 資料傳遞
- Vuex就是把資料拉出來,統一在外部存取,不需用props或emmits傳來傳去。
- 啟用Vuex後會多一個
\src\store\資料夾,其中index.js可以定義各種資料的存取import { createStore } from "vuex"; export default createStore({ state:{ isOpen: false, }, actions:{ handOpenState(context) { const isOpen = !context.state.isOpen; context.commit("OpenState", isOpen); }, }, mutations:{ OpenState(state, payload) { state.isOpen = payload; }, }, getters( isOpen(state) { return state.isOpen; }, ), modules: {}, });state:{}用來設定初始變數actions:{}用來設定讓組件用dispatch()呼叫的函數- 函式可以傳入
context參數(用context.state就可取得state中的變數值),也可以有第二個參數,也就是外部傳進來的值 - 用
context.commit觸發muations中的函式以改變資料值
- 函式可以傳入
muations:{}用來改變state中資料值- 函式一般會傳入
state,用來取得state中的變數值及第二個參數,也就是actions傳進來的值 - 元件可以直接用 store.commit() 來執行
muations中的函式(但不是好的作法)
- 函式一般會傳入
getters:{}用來重組資料(類似computed),函式一般會傳入state,用來取得state中的變數值
- 從 Vuex 取出
useStore()函式,用store.state.isOpen便可取到定義在state中的變數,但建議改用store.getters.isOpen(或store.getters['isOpen'])const isOpen = computed(() => { //return store.getters.isOpen; return store.getters["isOpen"]; }); - 用
store.dispatch()觸發actions中的函式(盡量不要用store.commit()觸發muations中的函式直接來改值,這樣流程不一致不太好)<script> import { useStore } from "vuex"; export default { setup() { const store = useStore(); const handClickMenu = () => { store.dispatch("handOpenState"); }; return { handClickMenu }; }, }; </script>
9-3 useRoute 及 useRouter