``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

Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2. In my scenario, the data is fetched from an API and stored in multiple table formats. I require the abili ...

Utilizing JavaScript Callbacks in HTML Image Tags

Currently I am working on a small application and looking to include a YouTube section. I have come across a method for obtaining the user's YouTube icon: This is included in the head section of my code: <script type="text/javascript" src="http:/ ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

Is there a way to display a foundation.css drop-down menu using jQuery?

After attempting to create a navigation bar using foundation.css, I encountered an issue where the sub-menu does not appear when hovering over it with the mouse. The main question at hand is how to display the sub-menu of test on this specific webpage. D ...

Activate a .click() event on a hyperlink exclusively in mobile view

Currently, I am working on a WordPress website that utilizes a Table of Contents plugin. The plugin simply identifies headings and adds them to the table of contents. I am aiming to achieve a specific functionality on my website (). When the window width ...

Guide to setting up a Node, Express, Connect-Auth, and Backbone application architecture for server-side development

As someone who primarily works on the client-side, I have recently ventured into the realm of server-side JavaScript. My initial plan for my first Node.js application involves a server-side setup that primarily serves an empty shell along with a plethora o ...

Having difficulty locating audio files within a Next.js project

I am facing challenges when trying to import my audio files into a redux slice. Currently, I am attempting to retrieve my audio files from the app > public > audio directory. I have made efforts to access my audio files through 2 different director ...

Error: content within v-html directive not displaying as expected

The v-html content is not rendering correctly for me. Interestingly, when I remove the v-html in the first list item, it works fine. Take a look at my code below: <div> <br> <li v-html="`a`"> <ul> <li ...

Sort through an array of objects using a different array

I am looking to showcase projects based on specific skills. For instance, if I choose "HTML", I want to see all projects that have "HTML" listed in their array of skills. If I select multiple skills, then only display projects that have those exact skills. ...

Turn off Chrome's new tab preview thumbnails

Is there a method to prevent Google Chrome from displaying certain pages as thumbnails? I am inquiring because I am developing a website that contains confidential information. As it stands now, the sensitive data can be viewed in the thumbnail preview. ...

Manage a frame directly from the parent page

I am faced with a situation where I have a web page with two textboxes and a button. Unfortunately, I am unable to alter the contents of this page in any way. My goal is to find a way to automatically populate the first textbox with some text when the pag ...

Patience is key as we wait for the webpage to finish loading

I've been searching for a solution to this issue for quite some time without any success... On my webpage, I have a square texture as the background which is set to repeat in order to fill the entire page. However, when a user first enters my site, t ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

Anticipate the completion of Subject callback execution

Take a look at the code snippet below: const mA = async () => { try { const subscription = myEmitter.subscribe(url => getD(url)); const la=()=>{...}; return la; } catch (error) { throw error; } }; ...

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

Implementing pagination in React: A step-by-step guide

I am fetching data from the GitHub API, specifically from here Although I have all the necessary data to display, I want to limit it so that only 20 repositories are shown per page. In addition, I prefer not to use any frameworks or plugins for this task ...

The body in Express is set to "Cannot GET [route]" during the execution of asynchronous code

I am currently working on an express application that includes some articles stored in a Mongo database. As I wait for the mongoose model Article to load, the body of the request gets changed to: <!DOCTYPE html> <html lang="en"> < ...

Deciphering the Essence of Promise Sequences

In my NodeJS project, I am utilizing Promises and aiming to gain a better understanding of Promise.chains. Within the project, there is one exposed function: This main library function returns a promise and it is intended for users to call. After calling ...

Population of the global namespace in JavaScript without the need for the 'new'

After watching the Douglas Crockford video on JavaScript, one thing that caught my attention was his explanation of what happens when you forget to use new for a class. He mentioned that doing so would populate the global namespace, which in the browser is ...