在 main.js 中引入 pinia
// main.js
import { createApp } from "vue";
// pinia 引入
import { createPinia } from "pinia";
import App from "./App.vue";
import router from "./router/index.js";
// 引入css
import "./assets/style/index.scss";
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
在 store 文件下创建 user.js
// user.js
import { defineStore } from "pinia";
import { login, logout } from "@/api/login.js";
import { getToken, setToken, removeToken, setExpiresIn } from "@/utils/auth";
export const useUserStore = defineStore({
id: "userStore",
state: () => {
return {
token: getToken() || "",
user: {},
name: "yqcoder",
avatar: "",
roles: [],
permissions: [],
expires_in: -1,
};
},
actions: {
login({ username, password, code, uuid }) {
return new Promise((resolve, reject) => {
login({
username: username.trim(),
password: password,
code,
uuid,
}).then((res) => {
if (res.code !== 200) {
reject(res);
return window.$msg.error(res.msg);
}
const { data } = res;
// 保存token
setToken(data.access_token);
this.token = data.access_token;
// 保存到期时间
setExpiresIn(data.expires_in);
this.expires_in = data.expires_in;
resolve(data);
});
});
},
logout() {
return new Promise((resolve, reject) => {
logout()
.then(() => {
this.token = "";
this.roles = [];
this.permissions = [];
removeToken();
resetRouter();
resolve();
})
.catch((err) => {
reject(err);
});
});
},
removeToken() {
return new Promise((resolve) => {
this.token = "";
this.roles = [];
removeToken();
reject();
});
},
},
});
在组件中使用 store
<script setup>
import { computed } from "vue";
import { useUserStore } from "@/store/user.js";
let userStore = useUserStore();
let name = computed(() => {
return userStore.name;
});
</script>
<template>
<div>{{ name }}</div>
</template>
<style lang="scss" scoped></style>