从Vue Store提取代码到Login的正确方法.vue页面



我想知道我应该从存储中添加哪些部分代码并添加到Login.vue

和我如何抛出验证错误从API返回到商店,以便我可以处理他们在Login.vue

Login.vue

<template>My login form is here</template>
<script>
import { AUTH_AUTHENTICATE } from "@/modules/auth/store/index";
methods: {
loginFormSubmit() {
/** AFTER LOGIN SUCCESS FROM STORE,
WHAT CAN I HANDLE HERE SO THAT MY STORE IS CLEAN 
*/
this.$store.dispatch(AUTH_AUTHENTICATE, this.loginForm);

}
}
</script>

src/模块/认证/存储/指数

export const AUTH_AUTHENTICATE = "/api/auth/authenticate";
actions: {
[AUTH_AUTHENTICATE]: ({ commit }, loginForm) => {
toolsApi.get("/sanctum/csrf-cookie").then(() => {
toolsApi
.post("/api/auth/authenticate", loginForm)
.then(response => {
if (response.data.status == "success") {
const token = `Bearer ${response.data.data.token}`;
Cookie.set("AUTH-TOKEN", token);
toolsApi.defaults.headers.common.Authorization = Cookie.get(
"AUTH-TOKEN"
);
commit("loginStatus", true);
this.$router.push({ name: "dashboard.index" });
}
})
.catch(error => {
console.log("Error");
console.log(error);
});
});
}
}

任何关于更正我的代码的指导都将对我有很大帮助

/**** UPDATE/

API错误响应

{
"status": "error",
"message": "Validation errors.",
"errors": {
"email": [
"The email field is required."
],
"password": [
"The password field is required."
]
}
}

在商店

toolsApi
.post("/api/auth/authenticate", loginForm)
.then(response => {
if (response.data.status == "success") {
const token = `Bearer ${response.data.data.token}`;
Cookie.set("AUTH-TOKEN", token);
toolsApi.defaults.headers.common.Authorization = Cookie.get(
"AUTH-TOKEN"
);
commit("setLoginStatus", true);
resolve(response.data.data);
// this.$router.push({ name: "dashboard.index" });
}
})
.catch(error => {
reject(error);
});

尝试从[AUTH_AUTHENTICATE]动作返回toolsApi.get(...),然后像承诺一样访问它。另一种抛出异常并在登录页面捕获它的方法。

最新更新