Implement a Vue binding that applies an active class on click, replacing the previous one

I have a loop that dynamically adds div sections to the page. I want the first one to be selected on page load, and then when another one is clicked, it should become active while the previous one loses its active status.

I attempted the code below but it is not working as expected. Any ideas for improvement?

<div class="col-sm-6" v-for="(area, index) in areaSections"> 
    <section class="monitoring-areas section" v-on:click="changeActive()"> 
        <h3>
          Area {{index + 1}}: {{area.title}}
          <span class="section-image hidden-xs hidden-sm"> 
            <i class="icon icon-zoom"></i> 
            <router-link to="/edit-monitoring-area">
              <i class="icon icon-pen"></i>
            </router-link>
          </span>
        </h3>                         
        <div class="section-content" v-bind:class="{ active: area.isActive }"> 
            <div class="row"> 
                <div class="col-xs-5"> 
                    <div v-html="area.img"></div>                                      
                </div>                                                                     
            </div>                                 
            <div class="row hidden-lg visible-sm visible-xs visible-md"> 
                <div class="col-lg-7 col-sm-8 col-xs-7 mb"> 
                    <p class="fw700"><span class="green">Email Alerts:</span> Monthly</p> 
                </div>                                                                                                     
           </div>                             
        </div>                                                       
    </section>                                                  
</div>

<script>
    export default {
        name: 'monitoringAreas',
        data: function() {
            return {
                areaSections: [
                    {
                        title: 'Home',
                        address: {
                        street: '1517 Castillo St',
                        city: 'Santa Barbara',
                        state: 'CA',
                        postalCode: '93117'
                    },
                    img: '<img src="static/img/map-small-2.jpg" alt="map">',
                    alerts: 'Monthly',
                    isActive: true
                },
                {
                    title: "John's neighborhood",
                    address: {
                        street: '3142 West 4th St',
                        city: 'Santa Barbara',
                        state: 'CA',
                        postalCode: '93117'
                    },
                    img: '<img src="static/img/map-small-2.jpg" alt="map">',
                    alerts: 'Monthly',
                    isActive: false
                },
                {
                    title: "Near Work",
                    address: {
                        street: '174 Collegio Rd',
                        city: 'Santa Barbara',
                        state: 'CA',
                        postalCode: '93117'
                    },
                    img: '<img src="static/img/map-small-2.jpg" alt="map">',
                    alerts: 'Monthly',
                    isActive: false
                },
            ]
        }
    },
    methods: {
        isActive() {
            return this.isActive;
        }, 
            changeActive() {
                this.isActive = !this.isActive;
            }
        }
    }
</script>

Answer №1

Consider implementing the following approach:

If you only want one section to be active at a time, create a data property called isActive to store the current active index. Pass the current index to the changeActive method and toggle the index if the active section is clicked again:

new Vue({
  el: '#app',
  data: {
    areaSections: [...],
    isActive: null
  },
  methods: {
    changeActive(index) {
      this.isActive = this.isActive === index ?  null : index
    }
  }
})

Make sure to include the index in the click listener for your template:

<section class="monitoring-areas section" v-on:click="changeActive(index)"> 

To apply the active class based on the new data property, use the following binding:

v-bind:class="{ active: index == isActive }"

You can view a complete example here: https://jsfiddle.net/wostex/63t082p2/73/

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

Tips for creating a function that utilizes a select option value

I'm struggling with a form that includes two select inputs. I want the second input to only be enabled if the first one has been selected. I attempted using an onclick event, but it didn't work out as expected. Can anyone provide assistance? (apo ...

Steps for Verifying the Legitimacy of an AJAX Request

In the process of creating a website where users are required to solve puzzles quickly, I am utilizing JavaScript to track the time taken for each puzzle. However, I am concerned about the possibility of users manipulating this data before it is sent to th ...

I'm just starting out with angular.js and could use some assistance in fixing the error below

I've encountered an error with my Angular code and would appreciate some assistance in resolving it. Please take a look at the code snippet below: <html ng-app> <head> <link rel="stylesheet" href="bootstrap.css"> <link rel="sty ...

What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with: bodyLength.forEach((el, i) => { console.log(`${values.bodyTitleEn2 + i.toString()}`); body.push({ title: [ { key: 'en', value: values.bodyTi ...

Is it acceptable for Single Page Web Apps to have multiple requests at startup?

I've been dedicated to developing a Single Page Web App (SPA) recently. The frontend is built with BackboneJS/Marionette, while the backend is powered by Java Spring :(. However, I've noticed that the application's start time could be sluggi ...

How can I implement jQuery Ajax to handle multiple elements on a single webpage?

I recently created a page where users can add items to their "favorites" list using the following JavaScript code: $(function(){ $('.doit-01234').click(function (e) { e.preventDefault(); $.ajax({ url: "https://www.domain. ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

Items seem to vanish into thin air and become immovable when attempting to relocate them

I am attempting to create a unique grid layout with 3x3 dimensions, where each grid item represents a fragment of a single image. These items should have the capability to be dragged and dropped inside another 3x3 grid, in any desired sequence. I have hit ...

Issues with @material-ui/core and react-bootstrap imports are causing disruptions to the NextJS build process

After researching, I've come to realize that this issue is common among developers. Unfortunately, none of the solutions I found have worked for me. During npm run dev mode, everything in the project functions as expected, with all imports working se ...

Optimizing Backend Access with Laravel and Vue JS: How to Choose the Most Effective Approach

Currently, I am utilizing Laravel API passport to handle authentication in my Single Page Application (SPA) built with Vue. At the moment, whenever I need to access the backend server, I have to include a header in order to be allowed through the protected ...

The alert() function in PHP does not function as expected and instead prints to the console

My attempt to display an alert is not working and I'm not sure what I might be missing. Can someone please help me pinpoint the issue? //my.php if(mail($to, $subject, $message, $headers)) { $message = "Mail sent."; echo "<script type=&apo ...

Issues arise with Vue.js's declarative rendering functionality after the bundling process with webpack

Here is a snippet from my index.html file: <!doctype html> <html><head> <body> <h1>ES</h1> <div id="app"> {{ message }} </div> <script src="dist/main.js" type="text/javascri ...

I am leveraging AngularJS to display a modal window with Bootstrap and Spring servlet integration

In my project, I am utilizing AngularJS to display multiple pages. One of these pages contains a smart-table where I showcase the details of "users". When I wish to edit one of the users, I aim to display the edit page as a popup window. Below is an excer ...

What are some effective ways to optimize a scrolling script?

Within my div element, I have a list of ordered elements (ol) that I am manipulating with drag and drop functionality using jQuery Nestable. If you could help me troubleshoot this issue, it would be greatly appreciated: How to scroll the window automatical ...

Exploring the Depths of Scope Hierarchy in AngularJS

Upon inspecting the _proto__ property of an object I created, it is evident that it has been inherited from Object. https://i.stack.imgur.com/hcEhs.png Further exploration reveals that when a new object is created and inherits the obj object, the inherit ...

Trouble accessing Vue component on the website

I attempted to execute the code from the Vue docs regarding components, but unfortunately, the component isn't appearing as expected. What could be causing this issue? <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue&q ...

The Vuex state or getters consistently yield 'undefined'

After creating some modules in Vuex 4, I am faced with an issue where I am unable to retrieve any data from it. It is possible that the data is not being saved or there might be a flaw in my logic. store/mutation-types.js export const SET_LOCALE = &apos ...

SVGs do not display on iPhones

Having some issues with my code - specifically, I have an SVG animation that seems to work on all devices except iPhones. I've been struggling to find a solution. Here is the code snippet for the SVG: <div class="contenuto-svg"> <svg vi ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...