繁体   English   中英

如何在 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属性。 检查链接以更好地理解https://v2.vuejs.org/v2/guide/list.html#Maintaining-State

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM