首页 > 解决方案 > Vue js 问题从 API 调用 url

问题描述

我正在尝试从 API 显示商店 URL。API 中有不同的 URL 可用,在输出中,它们显示为一个链接。如何在不同的行中显示 URL?

我的Vue代码:

<a v-bind:href=“storeUrl”&gt;
{{storeUrl}}
</a>

我的脚本:

....
computed:{
storeUrl() {
return this.games.store.map(({{url}}) => url).join(‘ ’)
},
}

我正在使用https://api.rawg.io/api/games API

这是当前的输出:

标签: javascriptapivue.jsurl

解决方案


用实际例子更新

首先,不要将它们加入计算中,然后使用 v-for 实现,这样的东西应该可以工作。

基本上这当然是我自己的想法,但是基于实际的 API 数据,这样的事情应该可以工作,在一个循环中循环,我绘制数据只是为了便于使用,你最终会得到类似的东西:

[
   {
      key: 'gta-v',
      storeUrls: [
         {
            key: 'steam',
            url: 'http:// ...'
         },
         {
            key: 'riot',
            url: 'http:// ...'
         }
      ]
   },
   {
      key: 'fortnite',
      storeUrls: [
         {
            key: 'steam',
            url: 'http:// ...'
         },
         {
            key: 'riot',
            url: 'http:// ...'
         }
      ]
   }
]

使用它,我们还可以在模板中加倍使用 v-for,并按游戏对数据进行排序,并为每个游戏循环通过它的 storeUrl 以获得一个漂亮的干净列表,这也利用了实际键的使用,而不是索引。

<template>
   <div class="root">
      <div class="game" v-for="game in games" :key="game.key">
         <h1>{{ game.key }}</h1>
         <a v-for="store in game.storeUrls" :href=“store.url” :key="store.key">
            {{store.url}}
         </a>
      </div>
   </div>
</template>

export default {
   data() {
      return {
         myData: null
      }
   },

   computed: {
      games() {
         if (!this.myData) return [];
         return this.myData.results.map(game => {
            key: game.slug,
            storeUrls: game.stores.map(store => {
               return {
                  key: store.store.slug,
                  url: store.url_en
               }
            });
         });
      }
   },

   methods: {
      getData() {
         // However you do it, but the base data, with no mapping.
         this.myData = axios.get('...'); 
      }
   }
}

推荐阅读