You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue调用登录API出现TypeError: Cannot read properties of undefined (reading 'input')

解决Vue登录API调用时的"Cannot read properties of undefined (reading 'input')"错误

错误原因分析

该错误表明代码尝试读取一个未定义对象的input属性,核心原因大概率是组件数据对象初始化不完整或函数内this指向异常,导致无法正确访问input变量。

排查与修复步骤

1. 检查data中的input对象定义

确保组件data选项里正确初始化input对象,且字段名与接口要求一致:

export default {
  data() {
    return {
      input: {
        correo: '', // 与接口请求体的`correo`字段对应,替换原绑定的`email`
        password: ''
      },
      vendedor: {}
    }
  },
  // ...其他代码
}

注意:原问题中HTML绑定用了input.email,但接口请求体字段是correo,字段名不匹配不仅会触发错误,还会导致接口无法接收正确参数,必须统一。

2. 确认login方法的this指向

如果login方法用箭头函数定义,会导致this指向全局对象而非组件实例,无法读取input。需改为普通函数:

methods: {
  async login() {
    try {
      const response = await axios.post('http://localhost:8080/api/vendedor/login', {
        correo: this.input.correo,
        password: this.input.password
      })
      // 处理接口返回的商家数据
      this.vendedor = response.data
      // 执行后续登录验证逻辑
    } catch (error) {
      console.error('登录失败:', error)
    }
  }
}

3. 修正HTML的v-model绑定

确保模板中v-model的绑定路径与data定义完全一致:

<template>
  <div>
    <input type="email" v-model="input.correo" placeholder="邮箱">
    <input type="password" v-model="input.password" placeholder="密码">
    <button @click="login">登录</button>
  </div>
</template>

4. 验证请求体格式一致性

确认axios请求体的字段名与Postman中使用的完全匹配(即correo和password),避免因参数不匹配引发接口异常,间接导致代码报错。

内容的提问来源于stack exchange,提问作者shesho47

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:40:58