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

Vue.js组件中方法无法访问data属性问题求助

解决Vue中"username is not defined"错误及相关问题

你的代码存在两个关键问题导致报错:

  • 箭头函数导致this指向异常:methods中的addUser使用箭头函数定义,箭头函数不会绑定自身的this,而是继承外层作用域的this,无法指向Vue实例,因此无法访问实例上的username属性。需要将箭头函数改为普通函数,通过this.username访问数据。
  • v-model指令语法错误:input标签里的:v-model="username"多了冒号,v-model是Vue的内置双向绑定指令,不需要用:(v-bind缩写)来绑定,正确写法是v-model="username"。

修正后的完整代码如下:

<template>
 <aside>
  <h3>Welcome {{ username }}</h3>
  <form action="">
   <h3>Welcome to smart-z todolist</h3>
   <p>Please write down your name</p>
   <div>
    <input type="text" v-model="username" id="userName" />
    <button type="submit" @click.prevent="addUser">Done</button>
   </div>
  </form>
 </aside>
</template>

<script>
 export default {
  name: "AsideSect",
  data() {
   return {
    username: "",
   };
  },
  methods: {
   addUser() {
     console.log(this.username);
   },
 },
 };
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:25:03