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

Vue多Props场景下如何向组件传递data数据?问题求助

Vue父组件向子组件传递data数据的正确方法

先拆解你之前写法的问题:

  • 第一种写法没加冒号:,此时info=this.data.information.item1会被当作字符串传递,而非你要的data数据,所以只能拿到字符串。
  • 第二种写法加了冒号,但多写了this.data——Vue模板的上下文就是当前组件实例,直接访问data里的属性即可,不需要this.data,错误的写法导致页面解析失败空白。
  • 第三种写法完全没必要用方法传值,而且方法名information和data里的属性重名,加上赋值逻辑混乱,自然会报重复键和未定义错误。

正确的传值步骤:

1. 子组件先声明要接收的Props

在你的ComponentName.vue里,先明确定义需要接收的属性:

<template>
  <div>
    <p>接收的prop值:{{ prop }}</p>
    <p>接收的info值:{{ info }}</p>
  </div>
</template>

<script>
export default {
  // 定义接收的props,指定类型和规则
  props: {
    prop: {
      type: String,
      required: true
    },
    info: {
      type: String,
      required: true
    }
  }
}
</script>

2. 父组件用v-bind(冒号简写)传递数据

回到App.vue,直接用冒号绑定data里的属性即可,不需要额外的方法:

<template>
  <!-- 冒号: 表示把右侧当作JS表达式解析,而非字符串 -->
  <ComponentName prop="something-else" :info="information.item1" />
</template>

<script>
import ComponentName from './components/ComponentName.vue'

export default {
  components: {
    ComponentName
  },
  data() {
    return {
      information: {
        item1: 'item 1 string',
        item2: 'item 2 string', 
        item3: 'item 3 string'
      } 
    }
  }
}
</script>

额外说明:

  • 如果要传递整个information对象,直接写:info="information"即可,记得把子组件props里的info类型改成Object。
  • 冒号:是v-bind的简写,核心作用是让右侧内容作为JavaScript代码执行,而非静态字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:39:18