vuex目录
文件内容
【store/index.js】
import { createStore } from "vuex";
import modules from "./modules";
const setupStore = (app) => {
let storeOptions = {
modules,
};
app.use(createStore(storeOptions));
};
export { setupStore };
【main.js】
import { createApp } from "vue";
import App from "./App.vue";
import { setupStore } from "./store";
const app = createApp(App); //创建vue实例
async function setupApp() {
/* vuex */
setupStore(app);
app.mount("#app");
}
setupApp();
【store/account/account.js】
import Cookie from "js-cookie";
export default {
namespaced: true,
state: {
userInfo: Cookie.get("userInfo") ? JSON.parse(Cookie.get("userInfo")) : "",
tokenInfo: Cookie.get("tokenInfo") ? JSON.parse(Cookie.get("tokenInfo")) : "",
permissions: null,
roles: null,
},
getters: {},
mutations: {
setUserInfo(state, user) {
//用户信息,随用随存,不设时限,随浏览器关闭而清除
state.userInfo = user;
if (user) {
Cookie.set("userInfo", JSON.stringify(user));
} else {
Cookie.remove("userInfo");
}
},
setTokenInfo(state, token) {
//token信息,执行登录操作时进行保存,时间7天
state.tokenInfo = token;
if (token) {
Cookie.set("tokenInfo", JSON.stringify(token), {expires: 7});
} else {
Cookie.remove("tokenInfo");
}
},
},
actions: {
setUserInfoAsync(context, user) {
context.commit("setUserInfo", user);
},
},
};
【use-demo.vue】
<template>
<div class="home tlc"></div>
</template>
<script>
import { useStore } from "vuex";
export default {
setup() {
const $store=useStore()
console.log($store.state.account.userInfo)
console.log($store.getters.account.xxx)
$store.commit("account/setUserInfo",xxx)
$store.dispatch("account/setUserInfoAsync",xxx)
},
};
</script>
<style scoped lang="less"></style>
mapState、mapGetters、mapMutations、mapActions封装
【mapState】
【mapGetters】
【mapMutations】
【mapActions】
标签:配置,tokenInfo,state,Cookie,userInfo,vue3,import,vuex,store
From: https://www.cnblogs.com/huihuihero/p/16730161.html