:::

10-2 modules 用法

  1. 可以把特定功能獨立出來,避免 store 太擁擠
  2. 例如做一個Auth認證功能,先在 store 下建立 \Auth\index.js
    export default {
      namespaced: true,
      state: {
        token: "",
      },
      actions: {
        handSetToken({ commit }, token) {
          commit("setToken", token);
        },
      },
      mutations: {
        setToken(state, token) {
          state.token = token;
        },
      },
      getters: {
        getToken(state) {
          return state.token;
        },
      },
    };
    

    namespaced 一旦設為 true,在使用時就要加上模組名稱,如「Auth/xxxx」

    store.dispatch("Auth/handSetToken", "Acbz1x3WQw4eq9qilpFjregn");
    console.log("TOKEN =>", store.getters["Auth/getToken"]);

     

  3. 在 \store\index.js 引入之
    import { createStore } from "vuex";
    import state from "./state.js";
    import actions from "./actions.js";
    import mutations from "./mutations.js";
    import getters from "./getters.js";
    
    import Auth from "./Auth";
    
    export default createStore({
      state,
      actions,
      mutations,
      getters,
      modules: {
        Auth,
      },
    });
    

     

  4. 在 App.vue 使用該 modules
    <script>
    import { onMounted } from "vue";
    import { useStore } from "vuex";
    export default {
    
      setup() {
        const store = useStore();
    
        onMounted(() => {
          store.dispatch("Auth/handSetToken", "Acbz1x3WQw4eq9qilpFjregn");
          console.log("TOKEN =>", store.getters["Auth/getToken"]);
        });
    
        return {};
      },
    };
    </script>

     

  5.  

:::

書籍目錄

展開 | 闔起

快速登入


https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1755%26tbsn%3D33

計數器

今天: 5109510951095109
昨天: 2489248924892489
總計: 8027091802709180270918027091802709180270918027091