如何在 vue.js 中呈现来自 api 的数据

how to rendering data from api in vue.js

我是 vue.js 的新手,我打算使用 API 制作一个新闻应用程序。 在这里我使用 v-for 来迭代一些代码。我认为 v-for 中存在问题。因为它给出了错误。错误已包含在此问题的结尾。 我使用以下代码来显示搜索结果

    <template>
      <div class="col-md-12">
         <div>
           <h2>Results</h2>
              <div class="card mb-3" v-for="item in resultList">
              <img class="card-img-top" src="" alt="Card image cap" height="100" width="200">
              <div class="card-body">
        <h5 class="card-title">{{ item.name }}</h5>
        <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
        <div class="button">
          <button type="button" class="btn btn-primary">Show more</button>
        </div>
        </div>
      </div>
       </div>
    </div>
     </template>
     <script>
     export default{
       props: ['resultList']
    }
</script>

以下代码用于获取 api 数据(搜索 api 数据)

<template>
         <div class="container1">
         <div class="form-group row">
            <label for="exampleInputPassword1">Search Music</label>
         <div class="col-lg-10">
         <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Type here" 
      @input="keypressed">
      </div>
      </div>
      </div>
     </template>
   <script>
      import axios from 'axios'
     export default{
      data () {
      return {
       newset: []
       }
       },
      methods: {
        keypressed () {
        var key = event.target.value
        axios.get('http://newsapi.org/v2/everything?q=' + key + 
       '&sortBy=publishedAt&apiKey=b5ac77726d0a4460bd82b57210b2efb7')
        .then(response => {
           this.newset = response.data.articles
         })
       .catch(e => {
           this.error.push(e)
         })
        this.$emit('newDataset', this.newset)
       }
       }
       }
      </script> 

但它给出了一个错误。错误是

      https://google.com/#q=vue%2Frequire-v-for-key  Elements in iteration expect to have 'v- 
      bind:key' 
     directives
     src\components\ResultArea.vue:5:5
     <div class="card mb-3" v-for="item in resultList">
      ^  

您需要添加 :key 绑定:

<div class="card mb-3" v-for="(item, index) in resultList" :key="index">

key 每个项目的值都应该是唯一的。如果您的列表项有任何 id,最好在此处使用此 id

<div class="card mb-3" v-for="item in resultList" :key="item.id">

要给 Vue 一个提示,以便它可以跟踪每个节点的身份,从而重用和重新排序现有元素,您需要为每个项目提供一个唯一的 key 属性。检查 link 以获得更好的理解 https://vuejs.org/v2/guide/list.html#Maintaining-State