步骤
1、auth/actions.js中添加auth方法,并精简login和signup方法,添加tryLogin用于保持登录状态
import axios from "axios";
export default {
async login(context, payload) {
context.dispatch('auth',{
...payload,
mode: 'login'
});
},
async signup(context, payload) {
context.dispatch('auth',{
...payload,
mode: 'signup'
});
},
async auth(context, payload) {
const mode = payload.mode;
let url = 'http://localhost:5216/api/Users/Login';
if (mode === 'signup') {
url = 'http://localhost:5216/api/Users/PostUser';
}
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
//id: context.getters.userId,
email: payload.email,
password: payload.password,
returnSecureToken: true
})
});
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to authenticate.');
throw error;
}
console.log(responseData);
localStorage.setItem('token', responseData.token);
localStorage.setItem('userId', responseData.userId);
context.commit('setUser', {
token: responseData.token,
userId: responseData.userId,
tokenExpiration: responseData.expiration,
});
},
tryLogin(context) {
const token = localStorage.getItem('token');
const userId = localStorage.getItem('userId');
if (token && userId) {
context.commit('setUser', {
token: token,
userId: userId,
tokenExpiration: null
});
}
},
logout(context) {
context.commit('setUser', {
token: null,
userId: null,
tokenExpiration: null
});
}
}
2、App.vue中调用tryLogin实现保持登录状态
export default {
components: {
TheHeader,
},
created() {
this.$store.dispatch("tryLogin");
},
};