Troubles with Vue.js when retrieving URL data from API

How can I properly display multiple store URLs from an API in separate lines?

Here is my vue code:

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

And here is my script:

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

The API I'm using is

Check out the current output here:

Answer №1

This solution addresses some issues following @chillin's response.

As mentioned in the comments, the reason for not displaying any store URLs is due to iterating over a non-existent object:

The issue, as pointed out by @chillin, is that you are looping through game.store instead of game.stores. When examining the game object, you'll see there is an array named stores, but not store.

It's important to wrap the anchor elements within <p> tags to prevent them from appearing on one line:

Before:

<a v-for="store in game.store" :href="store.url" :key="store.ID">{{store.url}}</a>

https://i.sstatic.net/0w4pJ.png

After:

<p v-for="store in game.stores" :key="store.ID">
    <a :href="store.url">{{store.url}}</a>
</p>

https://i.sstatic.net/QSKJU.png

Additionally, it’s worth considering using the index of the object as its key if duplicate IDs in the stores array could cause issues. Here’s how you can implement it:

<p v-for="(store, index) in game.stores" :key="index">
    <a :href="store.url">{{store.url}}</a>
</p>

...to prevent potential problems from occurring.

Here's a demonstration along with the revised codepen (the unused computed property storeUrl has also been removed).

Answer №2

Here's an Updated Example

To start, avoid combining them in the computed property and instead, try implementing a v-for loop approach like the one below:

This is my personal solution, based on the real API data. By nesting loops and mapping out the data for simplicity, you will achieve something similar to this structure:

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

This method also allows for a double-loop using v-for in the template, sorting the data by game and iterating through each game's storeUrls for a clean list presentation. This approach emphasizes utilizing actual keys over index values.

<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() {
         // Fetch the raw data without any mappings.
         this.myData = axios.get('...'); 
      }
   }
}

Answer №3

Having just started with Vue, I may not have the best solution. It seems logical to utilize the v-for directive to iterate through your store URLs.


If your watcher for gameId is functioning properly and finishing successfully, there should be no need to make any changes as the array of objects in this.game.stores will already exist.

You can then use something like this:

<a v-for="store in game.stores" :href="store.url" :key="store.store.id">{{ store.url }}</a>

Although I am unsure about the distinction between store.id and store.store.id, I assume that store.store.id serves as a unique identifier for a store and is appropriate to use as the key. (It would be wise to reference the API documentation for clarity on the IDs.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resizing an iframe dynamically based on the content of the URL without displaying a scroll bar using JavaScript

Within my application, there is a select drop-down menu that contains URLs. When a user selects a URL from the drop-down menu, I want to load that URL in an iframe with the appropriate content size. I am looking for a way to increase the height of the if ...

Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance: (function () { 'use strict'; angular.module("Dashboard") .controller("DashboardController", D ...

Preventing parent click events in AngularJS when clicking on a child element: Tips and tricks

I am facing an issue with a <div> that has a ng-click directive, but this <div> contains a child element also with a ng-click directive. The problem arises when the click event on the child element also triggers the click event of the parent el ...

Successful execution of asynchronous method in Node.js without any errors

When encountering duplicates in the config, I use the code snippet below: require('./ut/valid').validateFile() }); If a duplicate is found during validation, an error is sent like so: module.exports = { validateFile: function (req) { ... ...

What steps do I need to follow to get this AngularJs Gallery up and running

As I delve into expanding my knowledge in AngularJS, I've encountered some issues while trying to run code on Plunker. Could someone take a look at the code and point out what I might be doing incorrectly? The code snippet is provided below: var a ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Ensuring form field accuracy through server-side validation using Ajax - Mastering the art of Ajax

I am in need of implementing Ajax to validate my form fields, currently I have a javascript validation set up. Is it possible to reuse my existing javascript code and integrate Ajax for form validation? HTML Form <form method="post" action="ajax/valid ...

Guide to implementing final state injection using Vue Server-Side Rendering (SSR) and V8Js

The Vue SSR guide primarily focuses on setting up a nodejs server and briefly discusses using V8Js in the final chapter. While there is a section dedicated to final state injection, it doesn't seem to be compatible with V8Js. Is there a way to trans ...

Enhance the image with interactive shapes using JavaScript or JQuery

Looking to integrate dynamic shapes such as circles, rectangles, lines, ovals, etc. into images using a jQuery plugin or JavaScript. For example: https://i.sstatic.net/zXWCF.png Similar to how dynamic text can be added by typing in a textbox, I am lookin ...

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Top method for invoking own API in Node.js

Is it a good practice to call your own API for building a website? What is the most effective way to call your own API on the same server within a Node.js application? One option is to simply call the API directly. Another option is to use socket.io with ...

Tips for identifying a pair of numbers (with varying ranges) in which one number must be present at all times

I am currently trying to understand the regex I have implemented in Angular 2 using Typescript: /[0-5]?[0-9]?/ Surprisingly, this regular expression works flawlessly to match any valid minute from 1 to 59, even though it seems like an empty string would ...

Sorting strings in JavaScript based on a specified substring is an essential skill to have

I am working with an Array that contains strings in the following format: let arr = ["UserA | 3", "UserB | 0", "UserC | 2", "UserD | 1"] Each string represents a user and their corresponding ID. I want to sort this array based on the IDs at the end of eac ...

When utilizing CKEditor in conjunction with ExpressJS, HTML tags may be displayed in the browser

Check out my app.js code below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0> <meta http-equiv="X-UA-Compatible" content="ie= ...

Troubleshooting issue: Incompatibility between NODE.JS Passport and mongoose

Currently, I am diving into the world of Node.js and exploring all its features with the help of Scotch's tutorial (https://scotch.io/tutorials/easy-node-authentication-setup-and-local). Following the tutorial, I implemented what was suggested, which ...

An effective method for linking a value from one ng-model to another is by identifying and matching a specific string

I have been tasked with binding a value to one model based on the content of another model when it contains a string that starts with "https". For instance, there are two text fields each associated with a different model. <input type="text" ng-model= ...

Doesn't the use of asynchronous programming in Node.js lead to a potential StackOverflow issue?

Recently, I identified an issue with the Node.js (single-threaded) platform: As requests are handled by the server and they undergo processing until being blocked due to I/O operations. Once a request is blocked for processing, the server switches ba ...

What is the best method for distributing this array object?

I am faced with the task of spreading the following object: const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }]; I want to spread this array object and achieve the following format: form:{ ...

Hover over a div without affecting its anchor links

I wrote a basic function that reveals a hidden div .dida when hovering over another div .contacts $(document).on("mouseenter", ".contacts", function() { $(".dida").addClass("block") }) $(document).on("mouseleave", ".contacts", fun ...

How to download a file using AJAX in Laravel?

Is there a way to download a CSV file within an ajax call? I have an ajax request in my Laravel controller that successfully retrieves the file contents in the response. However, I am facing issues with actually downloading the file. Laravel controller c ...