Ways to add the class "active" to the initial element in a Vue.js for loop

I am currently diving into learning vue.js and am working on adding a list of elements. My goal is to apply the class="active" only to the first element in the for loop. Below is the snippet of my code:

<div class="carousel-inner text-center " role="listbox">
    <div class="item" v-for="sliderContent in sliderContents">
        <h1>{{ sliderContent.title }}</h1>
        <p v-html="sliderContent.paragraph"></p>
    </div>
</div>

This is how I want the first element to appear:

<div class="item active">
    <h1>WELCOME TO CANVAS</h1>
    <p>Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simply put them on your own Canvas</p>
</div>

The data retrieval process is functioning correctly, so all seems to be in order.

Below is my script code:

<script>
export default{
    data() {
        return {
            sliderContents: [
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simply put them on your own Canvas"
                },
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simply put them on your own Canvas"
                },
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simply put them on your own Canvas"
                },
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simply put them on your own Canvas"
                }
            ]
        }
    }
}

Your assistance would be greatly appreciated!

Answer №1

const TitleComponent = {
  template: `
    <h1>{{ title }}</h1>
  `,
  
  props: ['title'],
};

new Vue({
  components: {
    TitleComponent,
  },
  
  template: `
    <div>
      <title-component
        v-for="(item, index) in items"
        :class="{ 'active': index === 0 }"
        :title="item.title">
      </title-component>
    </div>
  `,
  
  data: {
    items: [
      { title: 'Heading One' },
      { title: 'Heading Two' },
      { title: 'Heading Three' },
    ],
  },
}).$mount('#app');
.active {
  color: blue;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
</head>
<body>
  <div id="app"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

This example illustrates a solution to a particular issue. Key points covered are as follows:

Within v-for loops, the parent scope properties can be fully accessed. The v-for directive also allows for an optional second argument to access the index of the current item.

For more information refer to: https://v2.vuejs.org/v2/guide/list.html#Basic-Usage

The v-for directive provides a second argument that gives you the index of the current item.

v-for="(item, index) in items"

In this case, to apply the active class to the first item, utilize an expression to check if the index is equal to 0 and bind it to the class attribute.

:class="{ 'active': index === 0 }"

Answer №2

To simplify the process, you can iterate through each element and check if the index is 0 before applying the active class (or any other desired class). Below is an example of how to define this class:

:class="{ 'active': index === 0 }"

Here is a practical demonstration using Bootstrap Tabs:

<ul class="nav nav-tabs tab-nav-right" role="tablist">
    <li role="presentation" :class="{ 'active': index === 0 }" v-for="(value, index) in some_array" v-bind:key="index">
        {{some_array[index]}}
    </li>
</ul>

If you need to apply multiple classes simultaneously, you can combine them as shown below:

:class="['tab-pane fade', (index === 0 ? 'active in' : 'something_else')]"

Answer №3

To add an active class to the first element in a loop, you can programmatically control the class using VueJS.

VueJS allows you to bind the class of an anchor tag (or any other element like an li tag) directly to the index of the element, so that when the VueJS variable linked to the index changes, the class also changes. For more details, refer to the following links:

This is the key solution:

:class="{current:i == current}

You can find a working example on this fiddle link and another blog post explaining how to dynamically control the class of an li element in VueJS:

https://jsfiddle.net/Herteby/kpkcfcdw/

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

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Provide the scope to the directive when calling the $uibModal.open method

I am interested in developing a custom directive that displays data based on the scope of its parent controller. Here is the directive's JavaScript code: (function () { 'use strict'; angular .module('blabla') ...

Is it possible to customize the close icons on the autocomplete feature in Material UI?

Is there a solution to change the icon while keeping its function when clicked? I am looking to replace this Icon <Autocomplete multiple id="checkboxes-tags-demo" options={top100Films} disableCloseOnSelect getOpt ...

NodeJS is capable of handling a limited number of requests at a time

Utilizing jQuery to send requests to a local server has been causing some issues. After sending approximately 4-7 requests, the port stops working without any visible error. Eventually, after a few minutes, some of the requests are successfully sent to the ...

Combining Java for the back-end and JavaScript for the front-end: a comprehensive guide

Looking for advice on integrating a Java back-end with a JavaScript, HTML 5 front-end in my web application. Any tips on passing content between the two languages? ...

What is the speed of communication for Web Worker messages?

One thing I've been pondering is whether transmission to or from a web worker could potentially create a bottleneck. Should we send messages every time an event is triggered, or should we be mindful and try to minimize communication between the two? ...

Creating duplicates of elements and generating unique IDs dynamically

I'm in the process of cloning some form elements and I need to generate dynamic IDs for them so that I can access their content later on. However, I'm not well-versed in Jquery/Javascript and could use some guidance. Here's a snippet of my ...

Encountering an error while trying to load a CSS file in a React project using webpack due

I'm currently working on a React project that utilizes styled components, and I've been attempting to integrate a CSS file as part of the react-image-gallery package. Following the instructions provided, I included the css-loader and style-loade ...

Prevent further execution upon callback in an AJAX request by stopping the click event function

When the function myClick() is called within itself instead of myLoad() on the first click, it leads to double execution of myClick() on the second click. => This results in two consecutive executions of the click event for #myBtn with just one click. ...

Tips for incorporating a page route with an HTML extension in Next.js

I'm facing a challenge in converting a non-Next.js page to Next.js while maintaining my SEO ranking. To preserve the route structure with HTML extensions and enhance visual appeal, I have outlined the folder structure below: Unfortunately, when acces ...

I require assistance in troubleshooting and repairing my HTML and JavaScript code

I am working on creating a feature where users can input their upcoming birthday date and receive an alert showing how many days are left until then. However, I encountered an issue where the alert displays NaN (Not a Number) before the birthday is entered ...

Top method for changing an array in javascript

I'm in the process of building a react application, and I've received the following array from an API call. var arrayLike ={ "2020-W1": [ { "type": "TAX_REFUND_IN_INT", &q ...

How to set the value of an `<input type="date"` in jQuery

Having trouble figuring out why this code isn't functioning properly. The input field I'm using is a simple 'input type="date"' setup like this.... <input type="date" name="Date"/> I am attempting to have the value automatically ...

What is the process for generating a collection of objects in a Mongoose Model?

I am currently working on creating a structure similar to this: var User = mongoose.model('Clicker', totalClicks: [ {type: Number, default: 0}, {type: Number, default: 0} ], I have explored various documentation resources related to ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

The ngAfterViewInit lifecycle hook does not get triggered when placed within ng-content

The ngAfterViewInit lifecycle hook isn't triggered for a Component that is transcluded into another component using <ng-content>, as shown below: <app-container [showContent]="showContentContainer"> <app-input></app-input> ...

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

JavaScript function to add or subtract

I need to include additional inputs for "+ and -" 60mm and 120mm in my function. How can I achieve this without turning all of them into separate functions? <template> <card class="card"> <h2>Measurement</h2> <form&g ...

Utilizing a npm module in a web browser following importing in Node.js

I recently installed an npm module, but I'm having trouble figuring out how to use it in the browser after importing it. First, I installed the npm module using the following command (using a dummy example module): npm install sample-module In my p ...

What is the best way to input variables into json values? [JavaScript]

let countryCode; let countryName; $(window).on("load", function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" }).done(function (json) { countryCode = json.country_code; $(function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" ...