You need to enable JavaScript to run this app. 为什么Vue3 setup中定义的方法调用时报Cannot read property 'username' of undefined
优惠活动
大模型
产品
解决方案
定价
更多

为什么Vue3 setup中定义的方法调用时报Cannot read property 'username' of undefined

问题根因
  • Vue 3 的setup函数在组件实例被创建之前就执行,不存在指向当前组件实例的this,你在test方法中尝试访问this.username时,this本身是undefined,自然就抛出了对应报错。
  • 你已经在setup的当前作用域内通过ref声明了username、password变量,同作用域下的test方法可以直接访问这些变量,不需要通过this调用。
修正方案

直接修改test方法的写法,去掉this,直接访问作用域内的ref变量即可:

const test = async () => {
  // 直接访问当前作用域的ref变量,需要手动加.value读取ref的值
  console.log(username.value)
}

补充说明:Options API 的methods中this是绑定到组件实例的,你在setup中返回给模板的ref变量会被自动挂载到组件实例上,且自动解包ref,所以methods里可以直接通过this.username访问,不需要加.value,这是两种写法的核心差异。

如果要对齐原来toLogin的完整业务逻辑,test方法的完整写法如下:

const test = async () => {
  const rep = await axios.post("login", {
    username: username.value,
    password: password.value,
  });
  console.log(rep)
  await router.push("/successlogin");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:42:00