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

Vue v-for循环中向子组件传递变量失败,新手Todo项目问题咨询

你代码中存在的错误及修正方案:

1. 父子组件传值语法错误

Vue中给子组件传动态值不能直接用{{}}写在组件标签内,需要用v-bind(简写为:)绑定属性:

  • 错误位置:Todo.vue的模板中<itemcomponent {{item}}></itemcomponent>
  • 修正为:<itemcomponent :item="item"></itemcomponent>

2. 模板属性绑定语法错误

子组件中给input的value绑定动态值同样不能直接用{{}},需要用v-bind:

  • 错误位置:itemComponent.vue的模板中<input type="text" value={{item }}/>
  • 修正为:<input type="text" :value="item"/>

3. v-for的key属性取值错误

你的result数组存储的是普通字符串,不存在item.id属性,key直接用循环的index或者item本身即可:

  • 错误位置:Todo.vue的模板中<div v-for="(item, index) in result" :key="item.id">
  • 修正为:<div v-for="(item, index) in result" :key="index">

4. 组件导入和注册位置错误

  • itemComponent是默认导出,导入时不能加解构大括号,且components选项是和data、methods平级的根选项,不能放在data内部
  • 错误位置:Todo.vue的script部分
  • 修正后的script部分:
import itemcomponent from "./itemComponent";

export default {
  // 这里不需要声明props:['item'],你没有用到父组件传的item属性
  components: {
    itemcomponent,
  },
  data() {
    return {
      nameme: "",
      upernameme: "",
      result: [],
    };
  },
  methods: {
    assignName: function () {
      this.upernameme = this.nameme.toUpperCase();
      this.result.push(this.nameme);
      this.nameme = "";
    },
  },
};

5. 按钮type属性错误

button的type属性没有click取值,你这里不需要提交表单,设置为button即可,避免默认触发页面刷新:

  • 错误位置:Todo.vue模板中<button type="click" @click="assignName">Submit</button>
  • 修正为:<button type="button" @click="assignName">Submit</button>

内容的提问来源于stack exchange,提问作者Naim R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:48:02