可以优化一下代码吗:putuserinf() { if ((this.phone.length == 11) && (this.password.length >= 6)) { this.State = true } else { this.State = false } if (this.State) { authApi.putuserinf({ account: this.account, idcard: this.idcard, phone: this.phone, password: this.password }) .then((res) => { if (res) { this.$router.push('/backend/tables/table5'); } else { this.submitState = "系统故障,修改失败" } }) } else { this.submitState = "请输入正确的账号和密码" } },
时间: 2023-06-12 07:07:36 浏览: 46
可以进行如下优化:
1. 将判断语句的结果直接赋值给 this.State 变量,避免重复判断。
2. 将 authApi.putuserinf() 的调用放到判断语句中,避免不必要的调用。
3. 将重复的字符串赋值提取出来,避免代码冗余。
改进后的代码如下:
```
putuserinf() {
const PHONE_LENGTH = 11;
const PASSWORD_LENGTH = 6;
const ERROR_MESSAGE = "请输入正确的账号和密码";
const FAILURE_MESSAGE = "系统故障,修改失败";
this.State = (this.phone.length === PHONE_LENGTH) && (this.password.length >= PASSWORD_LENGTH);
if (this.State) {
authApi.putuserinf({
account: this.account,
idcard: this.idcard,
phone: this.phone,
password: this.password
})
.then((res) => {
if (res) {
this.$router.push('/backend/tables/table5');
} else {
this.submitState = FAILURE_MESSAGE;
}
})
} else {
this.submitState = ERROR_MESSAGE;
}
},
```
这样的代码更加简洁易读,也更易于维护。