安装pinia 和 piniaPluginPersistedstate

在终端输入以下代码:

1
2
npm install pinia
npm i pinia-plugin-persistedstate

在vue应用实例中使用pinia

1
2
3
4
5
6
7
import {createPinia} from "pinia";
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
const app = createApp(App)
app.use(pinia)
app.mount("#app")

在src/stores/token.js中定义store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import {defineStore} from "pinia";
import {ref} from "vue";

export const userTokenStore = defineStore("token",()=>{
const token = ref('')
const setToken = (newToken)=>{
token.value=newToken;
}
const removeToken = ()=>{
token.value = ''
}
return{
token,setToken,removeToken
}
},
{
// 防止浏览器刷新丢失数据
persist:true
}
)

在组键中使用store

在登录事件中创建token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {userTokenStore} from "@/stores/token.js";
const userToken = userTokenStore()
const login = async ()=>{
let result =await userLoginService(loginData.value)
// if(result.code ===0){
// alert(result.msg?result.msg:"登录成功")
// }else{
// alert("登录失败")
// }
ElMessage.success(result.msg?result.msg:"登录成功")
//创建token
userToken.setToken(result.data)
// 路由跳转
router.push("/")
}

在请求拦截器中将pinia中token放入到请求头中,保证每次向后端请求数据都携带”Authorization”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import axios from "axios";
import {userTokenStore} from "@/stores/token.js";
// const baseURL = "http://localhost:8080"
const baseURL = "/api"
const instance= axios.create({baseURL})

instance.interceptors.request.use(
config =>{
let tokenStore = userTokenStore()
if(tokenStore.token){
config.headers.Authorization = tokenStore.token
}
return config
},
error => {
alert("token缺失")
return Promise.reject(error)
}
)