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

Vue3中无法正确向子组件传递Props,求助正确实现方法

问题分析与修正方案

你的核心问题是父组件已经循环传递单个新闻项的属性给子组件,但子组件错误地尝试循环整个新闻数组,同时props定义也存在问题。以下是符合Vue规范的正确实现方式:

1. 修正根组件(App.vue)

父组件通过v-for遍历新闻数组,给每个子组件传递单条新闻的title、id、body即可,当前场景不需要provide(仅跨层级传递数据时才需用到):

<template>
  <div>
    <app-news
      v-for="item in news"
      :key="item.id"
      :title="item.title"
      :id="item.id"
      :body="item.body"
    ></app-news>
  </div>
</template>

<script>
import axios from 'axios'
import AppNews from './AppNews.vue' // 必须引入子组件

export default {
  components: {
    AppNews // 注册子组件,否则无法使用
  },
  data() {
    return {
      news: []
    }
  },
  mounted() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts?_start=0&_limit=5')
      .then((resp) => {
        this.news = resp.data
      })
  }
}
</script>

2. 修正子组件(AppNews.vue)

子组件接收父组件传递的单条新闻属性,直接渲染即可,无需再循环数组:

<template>
  <div>
    <hr>
    <h3>{{ title }}</h3>
    <p>{{ body }}</p>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      required: true
    },
    id: {
      type: Number,
      required: true
    },
    body: {
      type: String,
      required: true
    }
  }
}
</script>

关键注意点

  • 父组件的v-for已经为每个子组件分配了单条新闻数据,子组件只需接收单个属性,不需要再处理数组。
  • 必须在父组件中引入并注册子组件,否则会出现组件未定义的错误。
  • props的类型校验能帮你提前发现数据传递的错误,建议保持这种规范写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:20:35