1.组件中methods代码
handleLogin() {
this.$refs.loginForm.validate(async (valid) => {
//async&&await代码
if (valid) {
this.loading = true;
try {
let result = await this.$store.dispatch(
"user/login",
this.loginForm
);
console.log(result, "01");
if (result && (result.code === 20000 || result.code === 200)) {
console.log('02');
this.$router.push({ path: this.redirect || "/" });
this.loading = false;
}
} catch (e) {
this.loading = false;
}
} else {
console.log("error submit!!");
return false;
}
//原本的.then代码
// if (valid) {
// this.loading = true;
// this.$store
// .dispatch("user/login", this.loginForm)
// .then(() => {
// this.$router.push({ path: this.redirect || "/" });
// this.loading = false;
// })
// .catch(() => {
// this.loading = false;
// });
// } else {
// console.log("error submit!!");
// return false;
// }
});
},
2.store中代码
async login({ commit }, userInfo) {
const { username, password } = userInfo
////async&&await代码
let result = await login({ username: username.trim(), password: password })
if (result && (result.code === 20000 || result.code === 200)) {
commit('SET_TOKEN', result.data.token)
setToken(data.token)
return new Promise(result)
}
Promise.reject(new Error('failed'));
//原本的.then代码
// return new Promise((resolve, reject) => {
// login({ username: username.trim(), password: password }).then(response => {
// const { data } = response
// commit('SET_TOKEN', data.token)
// setToken(data.token)
// resolve()
// }).catch(error => {
// reject(error)
// })
// })
},