Sharing information among v-for divisions - Vue.js

I am currently delving into the world of VueJS. While my code may not be the most elegant, it does the job almost as intended. The issue I am facing is that the API provides the title and href separately in different v-for loops, even though each loop only contains one item (0). My goal is to place the title in the <img> alt tags and also wrap the image in an <a> tag that includes another variable. I am aware that I cannot declare variables within {{ }}. Is there a way for me to create a temporary variable that can be used outside of each v-for? Or, perhaps this approach is flawed?

In my app.js file...

const app = new Vue({
    el: '#app',
    data: {
        results : []
    },
    methods: {
        getItems: function () {
            if (this.txtInput && this.mediaType) {
                axios.get("https://www.api.org/search?q="+this.txtInput+"&media_type="+this.mediaType)
                    .then(response  => this.results = response.data);
                this.mediaType = null;
            }
        }
    }
});

Following that, my HTML looks like this...

            <div id="app">
                <input id="txtName" v-on:keyup.enter="getItems" v-model="txtInput" type="text"><br>
                <input type="radio" id="image" value="image" v-model="mediaType">
                <label for="image">Image</label>
                <br>
                <input type="radio" id="audio" value="audio" v-model="mediaType">
                <label for="audio">Audio</label>
                <div v-for="result in results">
                        <div v-for="item in result.items">
                            <div v-for="data in item.data">
                                @{{ data.title }}<br>
                            </div>
                            <div v-for="link in item.links">
                                <img v-bind:src="link.href">
                            </div>
                        </div>
                </div>
            </div>

Answer №1

In the case where the data and links indices within the result.items are related to each other.
For example, the title of result.items.data[0] corresponds to the href of result.items.links[0].
To address this, you can specify an index in the v-for loop:

<div v-for="item in result.items">
  <div v-for="(data, index) in item.data">
    @{{ data.title }}<br>
    <img v-bind:src="item.links[index].href">
  </div>
</div>

An alternative approach is to optimize your code by utilizing a computed property, as suggested in the comments.

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

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

Navigating jQuery Tabs by Linking to a Specific Tab in a Separate File

I am currently using Bootstrap 3 to develop a basic website. On the about.html page, I have set up Tabs with various content. <ul class="nav nav-tabs" id="TabSomos"> <li class="active"><a href="#somos" data-toggle="tab">About Us</a> ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

What is the best method for designing a custom mask for the jQuery Masked Input Plugin that accommodates alphanumeric characters, spaces, and accented

Looking for a way to make a custom mask in jQuery Masked Input Plugin that allows alphanumeric characters, spaces, and accented characters? This is what I currently have: $.mask.definitions["A"] = "[a-zA-Z0-9 ]"; $("#input").mask("A?AAAAAAA"); However, ...

Prepare the column data for Vue Good-Table by formatting it beforehand

I've created a custom Vue.js component that retrieves orders from a Woocommerce store. These orders include product variations and are received in object form. Before displaying the data in a table, I need to format the object accordingly. This is a ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

Obtain a listing of values that appear multiple times within an array

I need a solution to find values that appear more than once in an array. The current code I have is quite complex. var arr = [1, 2, 3, 4, 2, 3]; var flag = {} var exist2arr = []; for(var i = 0; i < arr.length; i++){ for(var j = 0 ; j < arr.leng ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Limiting drag and drop in Three.js with specified distance thresholds

Is there a way to restrict the distance an object can be dragged and dropped in Three.js using DragControl? I am looking to set a maximum distance from the object's original position to prevent users from dragging it too far. ...

Exploring a different method for implementing animations during UI-router state transitions

My product owner presented me with a seemingly impossible challenge to create animations between states. I utilized ngAnimate and thought I had a brilliant solution - only to be told it wasn't what they wanted. "This isn't what I had in mind," h ...

managing the AJAX server's response

Struggling with a seemingly simple project where a button click should display a random saying generated from PHP, I don't have access to the PHP code and feel a bit lost. The issue seems to be in how I'm handling the server response (the handleS ...

Utilizing Backward and Forward Navigation with AJAX, JavaScript, and Window.History

TARGET Implement Ajax for fetching pages Utilize JavaScript to update the window URL Leverage Window History to preserve Ajax page for seamless forward-backward navigation without reloading the page Modify the Navigation bar's attributes (such as co ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Having trouble displaying images in Express JS

Here are the lines of code that I wrote in Express: res.write("The current temperature is "+temp+". "); res.write("Weather is currently "+weatherDes); res.write("<img src=" +imageURL+ ">"); res.send() ...

Tips for preventing the colors of all buttons from changing when only one is clicked in JavaScript

const tasks = `[{ "taskName": "Task 1", "image": "./images/task1.jpg", "description": "Task 1 description", "importance": 0 }, { "taskName": "Task 2", "image": "./images/task2.jpg", "description": "Task 2 description", ...

issues with jquery functionality on mobile devices

I'm currently working on a website where I've implemented a jQuery script to dynamically load specific parts of an HTML page with an ID of 'guts' into the main content area. The goal was to keep the menu consistent while only changing t ...

Retrieving a attribute from an element on a separate webpage

On my website, I have a list of links that use ajax to load new pages. Each of these new pages features a gallery of images with a main image. I am trying to figure out how to extract the source URL from the main image in order to display it as a thumbn ...

Is there a way for me to link my script for use in a Detail.cshtml file?

I have added the following script to my _Layout.cshtml shared master view: <script src="@Url.Script("~/Scripts/PromptToSave.js")" type="text/javascript"></script> Is there a way to include this script in a Details or index page that does not ...

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...