- 没改代码之前
<template>
<el-row type="flex" justify="center" align="middle" class="loginpage">
<!-- 用行包住表单 -->
<el-form ref="form" :model="form" label-width="80px">
<el-form-item label="账号">
<el-input v-model="form.username"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input type="password" v-model="form.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">提交</el-button>
<el-button @click="reset">重置</el-button>
</el-form-item>
</el-form>
</el-row>
</template>
<script>
export default {
data: function () {
return {
// 解决了发送请求,异步,正在发送着请求,结果还没回来,再次发送,只有等结果回来了再执行下一次的发送请求
issubmitting: false,
form: {
username: "",
password: "",
},
};
},
methods: {
onSubmit: function () {
if (this.issubmitting) {
return;
}
// 发送请求前判定
if (!this.form.username || !this.form.password) {
this.$message.warning("内容不能为空");
return;
}
this.issubmitting = true;
this.$axios({
method: "post",
url: "/login",
data: this.form,
}).then((res) => {
this.issubmitting = false;
console.log(res.data);
if (res.data.message == "登录成功") {
this.msg = this.$message.success("登录成功");
window.localStorage.setItem("newsbackendtoken", res.data.data.token);
this.$router.push("/");
} else {
this.msg = this.$message.error(res.data.message);
}
});
},
reset: function () {
// 这个也可以
// this.form.username = "";
// this.form.password = "";
this.form = {
username: "",
password: "",
};
},
},
};
</script>
<style lang="less" scoped>
.loginpage {
min-height: 100vh;
}
</style>
- 第一种方法
data: function () {
return {
msg: null,
};
},
methods: {
// 发送请求前判定
if (!this.form.username || !this.form.password) {
if (this.msg) {
// 如果已经有msg实例,先清除之前的实例
this.msg.close();
}
this.msg = this.$message.warning("内容不能为空");
return;
}
}
- 第二种方法
methods: {
onSubmit: function () {
// 发送请求前判定
if (!this.form.username || !this.form.password) {
this.$message.closeAll();
this.$message.warning("内容不能为空");
return;
}
}
}