10-2
modules 用法
- 可以把特定功能獨立出來,避免 store 太擁擠
- 例如做一個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"]);
- 在 \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,
},
});
- 在 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>
-