What is the best way to iterate through cards within a container using Vue.js?

Looking for a way to loop the content in a card multiple times within a container? You can use the v-for directive to render a list of items based on an array and change the data during looping. Here's an example code snippet:

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://the-allstars.com/vue2-animate/dist/vue2-animate.css">
</head>

<body>
    <div id="app">
        <div class="container">
            <div class="row">
                <div v-for="(card, index) in cardinfo" class="col-lg-3 col-md-3 col-sm-3 col-xs-12">

                    <div class="card text-center">
                        <img class="card-img-top" :src="card.image" alt="" width="100%">
                        <div class="card-block">
                            <h4 class="card-title">{{ card.title }}</h4>
                            <p class="card-text">{{ card.details }}</p>
                            <a class="btn btn-primary" href="#">Read More</a>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- vue code start from here -->
    <script>
        var dummyData = [{
            title: "This is the blog title",
            details: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa",
            image: "https://images.pexels.com/photos/39811/pexels-photo-39811.jpeg?h=350&amp;auto=compress&amp;cs=tinysrgb",
        }, {
            title: "This is the blog title2",
            details: "alrazy ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa",
            image: "https://images.pexels.com/photos/39811/pexels-photo-39811.jpeg?h=350&amp;auto=compress&amp;cs=tinysrgb",
        } {
            title: "This is the blog title3",
            details: "mohim ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa",
            image: "https://images.pexels.com/photos/39811/pexels-photo-39811.jpeg?h=350&amp;auto=compress&amp;cs=tinysrgb",
        }]
        var app = new Vue({
            el: '#app',
            data: {
                cardinfo: dummyData,
                currentIdx: 0
            },
            methods: {


            }

        })
    </script>
</body>

</html>

Answer №1

It appears that you haven't used the v-for directive in your code, and there's no need to employ a template like

{{ cardinfo[currentIdx].details }}
.

The Vue Official Guide defines the v-for directive as a way to render a list of items based on an array. It requires a specific syntax such as item in items, where items is the source data array and item serves as an alias for the iterated array element.

Within v-for blocks, we have complete access to parent scope properties. Additionally, v-for allows for an optional second argument representing the index of the current item.

A common usage of the v-for directive would be something like

v-for="(item, index) in items"
. I recommend referring to the above guide before proceeding with your code.

PS: Please pay attention to the concept of Key:

Here is a sample snippet:

var dummyData = [{
    title: "This is the blog title",
    details: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa",
    image: "https://images.pexels.com/photos/39811/pexels-photo-39811.jpeg?h=350&amp;auto=compress&amp;cs=tinysrgb",
}, {
    title: "This is the blog title2",
    details: "alrazy ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa",
    image: "https://images.pexels.com/photos/39811/pexels-photo-39811.jpeg?h=350&amp;auto=compress&amp;cs=tinysrgb",
}, {
    title: "This is the blog title3",
    details: "mohim ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa",
    image: "https://images.pexels.com/photos/39811/pexels-photo-39811.jpeg?h=350&amp;auto=compress&amp;cs=tinysrgb",
}]

var app = new Vue({
    el: '#app',
    data: {
        cardinfos: dummyData,
        currentIdx: 0
    },
    methods: {


    }

})
<link href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://the-allstars.com/vue2-animate/dist/vue2-animate.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
    <div class="container">
        <div class="row">
            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12" v-for="(cardinfo, index) in cardinfos" :key="index">

                <div class="card text-center">
                    <img class="card-img-top" :src="cardinfo.image" alt="" width="100%">
                    <div class="card-block">
                        <h4 class="card-title">{{ cardinfo.title }}</h4>
                        <p class="card-text">{{ cardinfo.details }}</p>
                        <a class="btn btn-primary" href="#">Read More</a>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

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

Enhancing vanilla HTML elements with custom props using React

const handleSelectChange = (e) => { console.log(e.target.getAttribute('id')); }; return ( <div> <select onChange={(e) => handleSelectChange(e)}> <option value="1-10" id=&qu ...

Calculate the difference to obtain a whole number from the overall length of the array [JavaScript]

Here is the code I am working with: function likes(names) { if (names.length == 0) { return 'no one likes this'; } else if (names.length >= 4) { return names[0]+ ', ' + names[1] + ' and' + names.length - 2 + &ap ...

Tips for running a function in CodeBehind triggered by jQuery?

In my Aspx code, I have the following: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebSite.View.Index" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> ...

Turning off form validation in AngularJS for a short period of time

Successfully implemented client side form validation using AngularJS, but now I want to test my server side validation by sending incorrect data. However, AngularJS is preventing me from doing so! Is there a way around this without disabling Javascript an ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

How to Activate a Change Event in Javascript using addEventListener when the checkbox has the checked attribute

Working on my script, I'm combining javascript and jquery together... // defining js variables const checkbox1 = document.getElementById('bill-to-different-address-checkbox'); const checkbox3 = document.getElementById('bill-to-shipped-a ...

Creating a duplicate of a class and accessing its properties

Allow me to present what may seem like a Frankenstein's monster idea, but please hear me out. I have a specific type that I work with: export enum detailsDataTypes { MACHINE = 'MACHINE', USER = 'USER', ABSTRACT = 'ABSTRA ...

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Utilizing query parameters and operators for managing collections

When working with GraphQL, what is the optimal approach to designing an "API query language" for filtering collections of items using various operators? For instance, in REST APIs, parameters like /family/people?height="192"&weight[]=">=65"&we ...

Click event not being triggered in Handlebar JS

VIEW DEMO Hey there, I've been struggling to implement a simple click event for dynamically loaded JSON data in an anchor tag. I've tried using both vanilla JavaScript and jQuery but haven't been successful in making it work. The same func ...

PHP file secured to only accept variables posted from HTML form

This is a basic HTML/AJAX/PHP script I have implemented. <form id="new_user" action="" method="post"> <div class="col-md-3 form-group"> <label for="username">Username</label> <input type="text" class="form-control" name ...

Vue.js is encountering an issue with NeDB where it is unable to locate the database files

Creating a Vue project: vue init webpack-simple nedbtest Installing the Nedb database: npm i nedb -S Modifying App.vue : <template> <div> <button @click="insert">Insert Data</button> <button @click="find">Find D ...

Invoke JavaScript functions upon the user closing a (pop-up) window

Is there a way to trigger a JavaScript function when the user closes a window? I've looked into JS event handlers and only found onunload, which activates the script when the user navigates away from the page, not necessarily closing the window. The ...

Exploring jQuery's AJAX capabilities in handling cross-domain requests and implementing Basic Authentication

I attempted the solutions provided in the suggested duplicate question, but unfortunately, they did not yield the desired outcome. I have been struggling to utilize AJAX to POST data to a remote server's API from a local PC client (testing on Chrome ...

The playwright brings the curtain down on a blank page without a single word

I am working with code snippets const {chromium} = require('playwright'); (async () => { const userDataDir = '\NewData'; const browser = await chromium.launchPersistentContext(userDataDir,{headless:false}); const pag ...

How come I'm encountering issues when trying to click on the "register-selection" button in my Bootstrap and JS setup?

I am facing a challenge while developing my website. I want to trigger an alert when the "register-selection" is clicked, but despite trying both Jquery and vanilla Javascript, I have not been successful. Even after searching online resources and ChatGPT f ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

The JSON.stringify function encounters difficulties when trying to format an object into

Why does JSON.stringify refuse to format objects and keep everything on a single line? <!DOCTYPE html> <html> <head> <script> var obj = { "a" : "1547645674576457645", "b" : "2790780987908790879087908790879087098", "c" ...

Sorting a collection based on an array value in Meteor JS

I'm currently facing the challenge of sorting a collection based on a specific value while another value is equal to something else. Please refer to the document below: { "_id": "zLFp8KptxzACGtAZj", "createdAt": "2015-05-28T21:11:57.044Z", ... ...