:::

10. Vuex 資料傳遞

  1. Vuex就是把資料拉出來,統一在外部存取,不需用props或emmits傳來傳去。
  2. 啟用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: {},
    });
    
    1. state:{} 用來設定初始變數
    2. actions:{} 用來設定讓組件用 dispatch() 呼叫的函數
      1. 函式可以傳入 context 參數(用context.state 就可取得 state 中的變數值),也可以有第二個參數,也就是外部傳進來的值
      2. context.commit 觸發 muations 中的函式以改變資料值
    3. muations:{} 用來改變 state 中資料值
      1. 函式一般會傳入 state ,用來取得 state 中的變數值及第二個參數,也就是 actions 傳進來的值
      2. 元件可以直接用 store.commit() 來執行 muations 中的函式(但不是好的作法)
    4. getters:{}  用來重組資料(類似computed),函式一般會傳入 state ,用來取得 state 中的變數值
  3. 從 Vuex 取出 useStore() 函式,用 store.state.isOpen 便可取到定義在state中的變數,但建議改用store.getters.isOpen(或store.getters['isOpen']
    const isOpen = computed(() => {
      //return store.getters.isOpen;
      return store.getters["isOpen"];
    });

     

  4. 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>

     

  5.  

:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D33%26tbdsn%3D1753

計數器

今天: 2593259325932593
昨天: 4096409640964096
總計: 7456121745612174561217456121745612174561217456121