能对它进行优化吗?然后说一下优化前后的差别。nnhandleLogin-n------this$refsloginFormvalidatevalid-=-n--------if-valid-n----------thisloading-=-true;n----------this$storen------------dispatchLogin-thisloginFormn------------thenres-=-n--------------if-rescode-==-200-n-------
可以尝试将代码中的重复操作进行提取和封装,以减少重复代码的出现,同时也可以提高代码的可读性和可维护性。优化后的代码如下:
handleLogin() { const validateLoginForm = () => { this.$refs.loginForm.validate((valid) => { if (valid) { this.loading = true; this.login(); } else { console.log("error submit!!"); return false; } }); };
const handleLoginSuccess = (res) => { if (res.code == 200) { let { loginInfo = {} } = res.data; // let redirect = !loginInfo.isUpdatePassword // ? "/updataPassword" // : this.redirect || "/"; this.$router.push({ path: "/" }).catch(() => {}); } else { this.$modal.msgError(res.message); this.getCode(); } this.loading = false; };
const handleLoginError = (err) => { this.loading = false; this.getCode(); console.log(err); };
const login = () => { this.$store .dispatch("Login", this.loginForm) .then(handleLoginSuccess) .catch(handleLoginError); };
validateLoginForm(); }
优化前后的差别是,优化后的代码将验证登录表单、登录成功、登录失败、登录操作等分别封装成了函数,代码可读性更佳,同时也提高了代码的可维护性。
原文地址: https://www.cveoy.top/t/topic/p5f 著作权归作者所有。请勿转载和采集!