What's the optimal method for implementing a Windows-style selection mode in JavaScript?

In Windows, you have the ability to select a folder by clicking on it once.

Currently, I am using Vuejs. I am interested in coding the same functionality with multiple arrays retrieved from my database and displayed using v-for.

My idea is to add a new column (select) to each array with a default value of 0. Then, I can implement a function that changes the select value to 1 when clicked, as well as apply a CSS class for visual distinction (such as blue border color).

At present, the element with the select column value of 1 is considered selected.

The process becomes more complex when trying to change the selection (i.e., selecting another array). I would need to first set all select columns' values to 0, remove any applied CSS classes, and then proceed with the new operation (as only one element should be selected at a time).

Any advice on how to achieve this? Thank you.

Answer №1

To implement this functionality with Vue.js, you just need to ensure your ViewModel is set up correctly. Your template should look like this:

<div>
  <!-- Pay attention to the dynamic :class bindings -->
  <div v-for="folder in list" class="folder-item" :key="folder.id"
    @click="onClick(folder)"
    :class="{ 'folder-item__active': folder === selected }">
      <span>{{ folder.folderName }}</span>
  </div>
</div>

In your component's JavaScript code, make sure to include:

Vue.extend({

  data() {
    return {
      // Initial list of folders
      list: [
        { folderName: 'Folder 1', id: 1 /* Some more data */ },
        { folderName: 'Folder 2', id: 1 /* Some more data */ },
      ],

      // Set selected to null for Vue.js reactivity tracking
      selected: null
    };
  },

  mounted() {

    // Update the folder list later on
    setTimeout(() => {
      this.list = [/* Updated list */]
      this.selected = null;
    }, 3000);
  },

  methods: {
    onClick(selectedItem) {
      this.selected = selectedItem;
    }
  }
});

There are three key points to note:

  1. Utilize dynamic :class bindings.
  2. Use the @click event handler to manage the selected folder.
  3. Whenever the list changes, reset the selected value to null. (Detecting changes by comparing references internally is straightforward and efficient.)

If your list frequently changes due to immutable data, adjust the logic based on a unique identifier:

<!-- Vue binding -->
:class="{ 'folder-item__active': folder.id === selected && selected.id }"

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

How to include a date in an Angular date input field

I've simplified some logic in this JSFiddle: http://jsfiddle.net/r7vyjg4h/ and it's functioning correctly. The HTML code is as follows: <div ng-controller="MyCtrl"> <div ng-repeat="line in lines"> <div style="display: inline- ...

Exploring the possibilities of node-webkit: node-odbc encounters a setback

Currently, I'm in the process of developing a desktop application utilizing node-webkit. The main functionality of the app involves querying an Oracle database. To establish the connection with the database, I have integrated node-odbc. To ensure tha ...

How can I generate rotating images using jQuery or JavaScript similar to the one shown here?

http://www.example.com/ On a website similar to example.com, I noticed that when hovering over one of the topics listed, the image rotates. I am interested in creating this interactive effect using either jQuery or JavaScript. Is there a method to access ...

How can we create dynamic animations with a counter in A-Frame?

I am looking for a more efficient method to sequentially execute animations one after the other, with each animation playing "X" number of times. Due to the randomness of animations being selected from arrays, I cannot consolidate them into a single long ...

Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can ...

Is there a way to customize the color of the active navbar item?

My navigation bar consists of 3 buttons and I'm looking to customize the text color for the active page. Additionally, I want to set a default button which is the first one in the list. I attempted using StyledLink from another solution but it doesn& ...

Searching and Sorting through JSON Data in React Native

I am currently expanding my knowledge in React Native and experimenting with filtering a JSON data set on a screen. My goal is to display only the filtered results on the screen. Would it be advisable for me to create a new component called FilteredTicket? ...

Transforming Yii1 code into Yii2 code (altering the language component)

I am facing an issue. I have a code in Yii1 that allows me to change the language on my site. echo CHtml::ajaxLink('EN', array('/'), array( 'type' => 'POST', 'success' => 'j ...

Joining a variable to an image URL using Vue.js

I recently started learning Vue.js and I'm struggling to figure out how to create an image with a dynamic src file path that includes a variable. Concatenating in Vue.js has been challenging for me. This is the image I currently have: <img :src=" ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Closing Modal Event in Beufy

Is there a way to initiate the close event in Beufy? I attempted to utilize the code provided below, however, there is no output in my console. I need to perform certain actions before closing. this.$modal.open({ parent: this, ...

Unable to install Vue-Cli

Currently running node 11.2.0 Continuously encountering this issue. Andrews-MacBook-Pro:vueTutorial aharris$ npm install -g @vue/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee6e1ebe5cebba0bea0ba" ...

I am a beginner in node.js and currently exploring the concept of asynchronous callbacks and how they function

When running the following code, "one" and "two" are displayed as output but "three" is absent. Can someone provide an explanation as to why "three" is not showing up in the output? Despite trying various methods, I am still unable to pinpoint the cause ...

What is the best way to set the first radio button as the default selection in Material UI?

The challenge I am facing involves a set of radio buttons representing dates from today to 30 days in the future. When a radio button is selected or active, it changes the background color. However, I would like the default selection to be the first radio ...

The functionality of the click event does not function properly for buttons that are dynamically generated using

Upon selecting the "Keyboard layout" option, JavaScript generates buttons dynamically. However, the click event does not work with these dynamically generated buttons. This issue is likely due to the fact that the element ".prices-tier" does not exist when ...

notifications failing to load properly on my rails application

I have created a rails application where users can comment on specific tasks. Whenever a new comment is posted on a task, all the users following that project should receive a notification. However, I am facing an issue where my ajax notifications are not ...

Is it possible to upload the WebRTC audio blob object using the file input element like a regular file without having to download it?

Greetings and thank you for taking the time to read my inquiry. I have been utilizing WebRTC to capture audio, successfully obtaining a blob object that I can manipulate using JavaScript to link the source of an audio element and play it as though it wer ...

Placing a material UI Radio button within a row cell on a table

Here is the current design snapshot: https://i.sstatic.net/yRFWD.png I am working with Material UI's radio button component and I want to ensure that each row in the table can be selected only once. Although I am able to select a single row using the ...

Mysterious symbols appearing in text/html encoding on Firefox

When I retrieve a text/html content from a ".txt" file using jquery.ajax(), everything works fine in other browsers except for Firefox. In Firefox, I see strange characters like ... This is my code: $.ajax({ url: "menuProcesso.txt", ...

The overflow property is set to scroll in jQuery, causing continuous scrolling until reaching a certain point, at which it

Continuously adding new chat messages will show the latest one, but eventually it stops scrolling down automatically. How do I resolve this issue? Thank you. http://jsfiddle.net/VMcsU/ $("#button1").click(function(){ $("<div>").html("text").app ...