Login + getInfo + Register 后端 API 书写, login + logout 前端书写
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { createStore } from 'vuex'
|
||||
import ModuleUser from './user'
|
||||
|
||||
export default createStore({
|
||||
state: {
|
||||
@@ -10,5 +11,7 @@ export default createStore({
|
||||
actions: {
|
||||
},
|
||||
modules: {
|
||||
user: ModuleUser,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import $ from 'jquery'
|
||||
|
||||
export default {
|
||||
state: {
|
||||
id: "",
|
||||
username: "",
|
||||
photo: "",
|
||||
token: "",
|
||||
is_login: false,
|
||||
},
|
||||
getters: {
|
||||
|
||||
},
|
||||
// 同步事件
|
||||
mutations: {
|
||||
// 更新用户信息
|
||||
updateUser(state, user){
|
||||
state.id = user.id;
|
||||
state.username = user.username;
|
||||
state.photo = user.photo;
|
||||
state.is_login = user.is_login;
|
||||
},
|
||||
// 更新用户 Token
|
||||
updateToken(state, token){
|
||||
state.token = token;
|
||||
},
|
||||
// 退出登录
|
||||
logout(state){
|
||||
state.id = "";
|
||||
state.username = "";
|
||||
state.photo = "";
|
||||
state.token = "";
|
||||
state.is_login = false;
|
||||
}
|
||||
},
|
||||
// 异步事件
|
||||
actions: {
|
||||
// 登录函数
|
||||
login(context, data){
|
||||
$.ajax({
|
||||
url: "http://localhost:3000/user/account/token/",
|
||||
type: "POST",
|
||||
data: {
|
||||
username: data.username,
|
||||
password: data.password,
|
||||
},
|
||||
success(resp) {
|
||||
// console.log(resp.token, "\n成功了\n", resp.error_message);
|
||||
if(resp.error_message === "success"){
|
||||
/*
|
||||
登录成功则将获取到的 resp 里的 token 传给 mutations 里的
|
||||
updateToken 方法,对用户 token 信息进行更新
|
||||
*/
|
||||
context.commit("updateToken", resp.token);
|
||||
data.success(resp);
|
||||
} else {
|
||||
data.error(resp);
|
||||
}
|
||||
|
||||
},
|
||||
error(resp) {
|
||||
data.error(resp);
|
||||
},
|
||||
});
|
||||
},
|
||||
// 获取登录成功后的用户信息
|
||||
getinfo(context,data){
|
||||
$.ajax({
|
||||
url: "http://localhost:3000/user/account/info/",
|
||||
type: "GET",
|
||||
headers: {
|
||||
Authorization:
|
||||
"Bearer " + context.state.token,
|
||||
},
|
||||
success(resp) {
|
||||
if(resp.error_message === "success"){
|
||||
// 更新用户信息
|
||||
context.commit("updateUser",{
|
||||
...resp, // 解构 resp 中的内容
|
||||
is_login: true, // 登录成功,将 is_login 置为 true
|
||||
});
|
||||
data.success(resp); // 调用回调函数
|
||||
} else {
|
||||
data.error(resp);
|
||||
}
|
||||
},
|
||||
error(resp) {
|
||||
data.error(resp);
|
||||
},
|
||||
});
|
||||
},
|
||||
logout(context){
|
||||
context.commit("logout");
|
||||
}
|
||||
|
||||
},
|
||||
modules: {
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user