Vue.js中如何处理接口响应实现按状态条件路由跳转
登录页路由跳转功能修复方案
现存问题梳理
.then回调语法错误:使用圆括号包裹含条件判断的多行逻辑,会触发语法解析失败,多行函数体必须使用花括号包裹- 响应字段取值错误:
response.status是axios返回的HTTP协议状态码(数值类型,如200),后端定义的status业务字段位于response.data中,原有代码永远无法匹配判断条件 - 响应式变量未声明:请求结束的回调中使用了
this.loading,但data中未预先定义该变量,会触发运行时警告 - 表单类型错误:密码输入框设置为
text类型,会明文展示输入内容,应调整为password类型
修正后完整代码
<template> <div> <h3 class="text-center text-primary font-weight-bold">用户登录</h3> <div class="row"> <div class="col-md-6"> <form @submit.prevent="userLogin"> <div class="form-group"> <label>用户名</label> <input type="text" class="form-control" v-model="userData.email"> </div> <div class="form-group"> <label>密码</label> <input type="password" class="form-control" v-model="userData.password"> </div> <button type="submit" class="btn btn-primary">登录</button> </form> </div> </div> </div> </template> <script> export default { data() { return { userData: {}, loading: false } }, methods: { userLogin() { this.loading = true this.axios .post('http://localhost:8000/api/login', this.userData) .then(response => { // 读取后端返回的业务状态字段 if (response.data.status === 'success') { this.$router.push({ name: 'home' }) } else { this.$router.push({ name: 'login' }) } }) .catch(err => console.log(err)) .finally(() => this.loading = false) } } } </script>
逻辑验证说明
- 语法修正后,回调内的条件判断可正常执行
- 调整取值路径后,可准确匹配后端返回的
success/failed状态,触发对应路由跳转 - 补充
loading状态声明后,可在请求加载期间禁用提交按钮,避免用户重复点击提交
内容的提问来源于stack exchange,提问作者mukesh kapoor
相关产品推荐
相关产品推荐

