【问题标题】:TypeError: Cannot read property 'title' of undefined. Vue.jsTypeError:无法读取未定义的属性“标题”。 Vue.js
【发布时间】:2023-03-17 21:36:01
【问题描述】:

使用 axios API 制作hackernews 克隆。数据不会传递给 NewItem.vue 组件。返回错误 — TypeError: Cannot read property 'title' of undefined. 告诉我代码有什么问题。为什么不传输数据?问题可能出在道具上吗?

NewItem.vue:

<template>
    <div class="news-item">
        {{ story.title }}
    </div>
</template>

<script>
export default {
  props: ['story'],
};
</script>

Home.vue:

<template>
  <div class="home">
    <div class="news-view">
      <div class="news-list-nav">
        <span>1/23</span>
      </div>
      <div class="news-list">
        <ul>
          <li class="news-item">
            <news-item v-for="story in stories" :key="story.id">
            </news-item>
          </li>
        </ul>
      </div>

    </div>

  </div>
</template>

<script>
import axios from 'axios';
import NewsItem from '../components/NewsItem.vue';

const BASE_URL = 'https://api.hnpwa.com/v0/news/1.json';
export default {
  components: {
    NewsItem,
  },
  data() {
    return {
      stories: [],
    };
  },
  created() {
    axios
      .get(BASE_URL)
      .then((response) => {
        this.stories = response.data;
      });
  },
};
</script>

【问题讨论】:

    标签: javascript json vue.js axios


    【解决方案1】:

    您没有将 prop 从父组件传递给子组件,这样做:

    <news-item v-for="story in stories" :key="story.id" :story="story"></news-item>
    

    【讨论】:

    • 不客气。如果解决了您的问题,请将答案标记为解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多