``Incorporating Vue.js: A Guide to Emphasizing the Chosen Selection from Numerous Lists

I am currently utilizing Vue.js and have multiple lists displayed, but I only wish to select and highlight one element at a time. Currently, every click results in multiple items being highlighted. I hope that explanation is clear. Below are the snippets of my code:

<template>
 <div>
    <div class='list-group'>
      <a v-for='(product, idx) in adslCapped' class='list-group-item'
         v-on:click='toggleActiveIndex(idx)' 
         :class="{'active': idx == activeIndex}" >
      {{product.name}}
      </a>
    </div>


    <div class='list-group'>
       <a v-for='(product, idx) in fibre' class='list-group-item'
          v-on:click='toggleActiveIndex(idx)' 
          :class="{'active': idx == activeIndex}" >
       {{product.name}} 
       </a>
    </div>
  </div>
</template>

    data: {
      activeIndex: null
    },
    methods: {
       toggleActiveIndex: function(index){
         this.activeIndex = index
       }
    }

As you can observe, there are two lists, but when I click on the first item of the first list, it highlights the first item in both lists. Please be aware that these snippets represent the issue I am facing.

Answer №1

If you want to highlight only one item in all the lists within your current app structure, consider adding a new variable that will represent the active list.

Then, adjust the condition for applying the active class by checking if the index matches the active index and if the list matches the active list.

HTML

<div id="app">
  <div class='list-group'>
  <a v-for='(product, idx) in adslCapped' class='list-group-item'
     v-on:click='toggleActiveIndex(adslCapped, idx)' 
     :class="{'active': idx == activeIndex && adslCapped == activeList}" >
  {{product}}
  </a>
  </div>


  <div class='list-group'>
     <a v-for='(product, idx) in fibre' class='list-group-item'
        v-on:click='toggleActiveIndex(fibre, idx)' 
        :class="{'active': idx == activeIndex && fibre == activeList}" >
     {{product}} 
     </a>
  </div>
</div>

Script

new Vue({
  el: "#app",
  data() {
    return {
      activeIndex: null,
      activeList: null,
      adslCapped: ['a', 'b', 'c'],
      fibre: ['1244', '125215', '02150']
    }
  },
  methods: {
   toggleActiveIndex: function(list,index){
     this.activeIndex = index;
     this.activeList = list;
   }
  },
})

Check out the demo here

I hope this solution proves helpful!

Answer №2

Although it may seem like overkill for a simple scenario, one approach is to abstract the list into a component and store selected products separately.

Check out this example:

var productList = Vue.component('product-list', {
  props: {
    value: Object,
    products: Array
  },
  template: `
<div class="product-list"><a class="ist-group-item" :class="{'active': product.id === value?.id}" @click="selectProduct(product)" :key="product.id" v-for="product in products">{{product.name}}</a></div>`,
  methods: {
    selectProduct(product) {
      this.$emit('input', product)
    }
  }
})

var app = new Vue({
  el: "#app",
  data() {
    return {
      selected1: null,
      selected2: null,
      products: Array(5).fill(0).map((pr, id) => ({
        id: id + 1,
        name: `Product ${id + 1}`
      }))
    }
  },
  mounted() {
    //console.log(this.products)
  },
  methods: {}
});
.product-list {
  border: 1px solid black;
  padding: 5px;
  margin-top: 5px;
}

.ist-group-item {
  display: block;
  transition: all .3s ease-in;
}

.ist-group-item:hover {
  background: lightgray;
}

.ist-group-item.active {
  background: black;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <product-list v-model="selected1" :products="products">
  </product-list>
  <product-list v-model="selected2" :products="products">
  </product-list>

</div>

Answer №3

One of the main issues at hand is that activeIndex is a singular variable, making it impossible to use for setting the index in both lists simultaneously.

The root cause lies in not being able to distinctly specify which list should be activated upon clicking within the v-for loop.

new Vue({
  el: "#app",
  data: {
    list1: [{
        name: "Learn JavaScript",
        done: false
      },
      {
        name: "Learn Vue",
        done: false
      },
      {
        name: "Play around in JSFiddle",
        done: true
      },
    ],
    list2: [{
        name: "Learn JavaScript",
        done: false
      },
      {
        name: "Learn Vue",
        done: false
      },
      {
        name: "Play around in JSFiddle",
        done: true
      },
    ],
    active1Index: null,
    active2Index: null
  },
  methods: {
    toggleActive: function(list, index) {
      if (list === "list1") {
        this.active1Index = index
      } else {
        this.active2Index = index
      }
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

.active {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class='list-group'>
    <a v-for='(product, idx) in list1' class='list-group-item' v-on:click='toggleActive("list1", idx)' :class="{'active': idx == active1Index}">
      {{product.name}}
      </a>
  </div>


  <div class='list-group'>
    <a v-for='(product, idx) in list2' class='list-group-item' v-on:click='toggleActive("list2", idx)' :class="{'active': idx == active2Index}">
       {{product.name}} 
       </a>
  </div>
</div>

Answer №4

Big shoutout to all the incredible individuals who took the time to provide answers on stackoverflow. Julia's solution really came through for me! I am now in the process of incorporating it across my entire application and various lists.

A heartfelt thank you, Julia!

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

When clicking on the text areas, the Twitter-Bootstrap drop-down login automatically closes

Greetings! I am currently working on my first website design using JQuery. My project includes a dropdown login box created with Twitter-Bootstrap. Unfortunately, I'm facing some challenges with the JQuery script that controls the behavior of the logi ...

Find and conceal the object within the list that includes the term "Ice"

The teacher's assignment is to create a radio button filter that hides items with the word "Ice" in them, such as "Ice Cream" and "Iced Tea." Here is the current code I have been working on: <!DOCTYPE html> <html> <head> <me ...

Error message received when calling a function within a Vue watcher states "function is not defined"

My goal is to trigger a function in a Vue component when a prop changes using a watcher: props: [ 'mediaUrl' ], watch: { mediaUrl: function() { this.attemptToLoadImage(); } }, medthods: { attemptToLoadImage: function() { console ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

Persistent Angular Factory Variables Showing Outdated Data - Instances Stuck with Old Values

One of the challenges I faced was setting up a resource factory to build objects for accessing our API. The base part of the URL needed to be determined using an environment variable, which would include 'account/id' path segments when the admin ...

The readyState of Ajax is consistently anything but 4

I have encountered an issue with my JavaScript code. I am running these codes in order to display data based on user input. Despite there being no error connection and the connection happening properly, whenever I enter a name it always goes into the else ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

The 'fs' module does not seem to have an immediate impact; a server restart may be necessary for the changes to take

This NodeJS project involves starting the server with npm start. The project reads files from a folder called "./mydir/" using 'fs.readdirSync'. It then pushes these files into an array and prints them on the console. var fs = require('fs ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Automating Indesign with HTML5 and JavaScript through IDML files

I am currently working on automating IDML files. My goal is to display an IDML template in an HTML5 editor. Within the sample.idml file, I have a basic TextFrame containing the text "Hello World." After unzipping the file and navigating to the stories fol ...

Retrieve the Multer file name and/or file path

Just checking in on everyone's well-being. I'm currently struggling to retrieve the file path or name after uploading it to the folder. Whenever I try console logging req.files.path or req.files.filenames, it always returns undefined. Could someo ...

Make an axios request multiple times equal to the number of items in the previous response

In my project, I am using the axios library to convert addresses into their respective coordinates. First, I fetch a list of addresses from an API. Next, I take the RESPONSE object and use Google API to convert each address to coordinates. Finally, I wan ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

Testing an Angular factory that relies on dependencies using JasmineJS

I have a factory setup like this: angular.module("myServices") .factory("$service1", ["$rootScope", "$service2", function($rootScope, $service2){...})]; Now I'm attempting to test it, but simply injecting $service1 is resulting in an &ap ...

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

Find all relevant employee information at once without the need for iteration

I have structured two JSON arrays for employee personal and company details. By inputting a value in the field, I compare both tables and present the corresponding employees' personal and company information in a unified table. <html> ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Develop an onclick function with an href attribute

I am interested in transforming links into AJAX versions whenever possible. To achieve this, I plan to implement a function called replaceLinks that will add an onClick handler to each link on the page and trigger ajaxPageWSM(href). This is what I currentl ...