What's the best way to switch between colors in a Vue list?

I have a custom tree-view component that I'm working on:

<template>
    <li class="main__li list" :style="{'margin-left': `${depth * 20}px` ,'background-color': `${col}`}" @click="toggle(e); getEl($event)" :title="tree.name">{{tree.name}} </li>
  <ul v-show="isOpen" v-if="isFolder" class="ul__ctg list">
    <TreeView :tree="chld" v-for="(chld, inx) in tree.children" :key="inx" :depth="depth +1"></TreeView>
  </ul>
</template>

Here is the script where I'm trying to change the color of an item when clicked:

     getEl(e){
        this.col = 'blue'
        //how turn previous item`s color back?
        return this.tree.id
      },

I am struggling with reverting the color of the previously selected item back to its initial state. When I click on an item, it changes color as intended, but making sure the previous selection goes back to normal has been a challenge for me.

Answer №1

To meet your specifications, it is necessary to assign a default color to each tree object initially and then allow toggling on click.

Check out the Live Demo :

new Vue({
  el: '#app',
  data: {
    trees: [{
        name: 'Tree 1'
    }, {
        name: 'Tree 2'
    }, {
        name: 'Tree 3'
    }, {
        name: 'Tree 4'
    }],
    defaultColor: 'green'
  },
  mounted() {
    this.trees = this.trees.map(obj => {
        obj.color = this.defaultColor;
      return obj;
    });
  },
  methods: {
    getEl(index) {
        const changedColor = 'blue';
        this.trees = this.trees.map((obj, i) => {
            obj.color = (i === index) ? changedColor : this.defaultColor;
          return obj;
        });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <li v-for="(tree, index) in trees" :key="index" :style="{'background-color': `${tree.color}`}" @click="getEl(index)">{{tree.name}} </li>
</div>

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

AJAX is not displaying the expected output

Seeking help on calling a PHP method from JavaScript to query a database and integrate the results into JS functionality. The current 'console.log(output)' in my Ajax returns: "array (size=1) 'action' => string 'getResults&apos ...

JavaScript powered caller ID for web applications

I am currently working on an innovative project where I aim to automatically detect the phone number of a landline call to a specific device. While research led me to various packages like npm caller-id-node that work with desktop applications using the mo ...

Hide other dropdown when one dropdown is clicked

I am currently working with a dropdown data-filter in combination with the isotope plugin. My goal is to have the ability to close an open dropdown when another list item is clicked, and also have the arrow twirl down when the dropdown is open. I am seek ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Before beginning my selenium scripts, I need to figure out how to set an item using Ruby in the browser's localStorage

Before running my selenium scripts, I am attempting to store an item in the browser's localStorage. I attempted to clear the local storage using this command: driver.get('javascript:localStorage.clear();') This successfully cleared the lo ...

Using JSON with PHP to send data and receiving the response back with JavaScript

Despite exploring numerous questions and attempting various methods, I have been unable to find a solution that works. Here is my JavaScript file: function sendData() { var jsondata; var j = {"pub_id":"'+pid+'","a_type":"'+a_t&ap ...

Express.js automatically sets timeouts for requests to static files

I've been facing this issue for several weeks now - after launching, Express functions properly for a few hours and then suddenly stops serving static files. The situation is as follows: GET / 304 153ms GET /js/bootstrap.min.js 200 120000ms GET /img/ ...

Calculate a value within a MongoDB field

Hello everyone, I have a document in my collection that looks like this: { Player_Name: Sandeep Nair Player_TotalWeightedPoints: 80 Player_Rank: 23 } I have around 200 similar documents in my collection. The Player_Rank is determined by the total Weighted ...

The functionality of a Vue custom tooltip behaves strangely after clicking the button multiple times

I created this custom tooltip code that automatically closes after 2 seconds when a user clicks on a button, not just hovers over it. Initially, it works perfectly for the first two clicks, but then starts behaving strangely from the third click onwards. ...

Transferring properties from React Router to child components on the server side

For my Isomorphic app using React, react-router v3, and material-ui, it's crucial to pass the client's user agent to the theme for server-side rendering. This is necessary for MUI to properly prefix inline styles. Initially, the root component o ...

Issue with the AngularJS build in Yeoman

After setting up Yeoman and Bootstrap for an AngularJS project, I utilized the grunt server command for debugging and coding. However, when I tried using the 'grunt build' command, it generated a dist folder. Unfortunately, when I attempted to ru ...

Tips for displaying only the items that are currently visible in an AngularJS Dropdown

I am currently working with an AngularJs object that looks like this: $scope.data = {'options': [{ "id": 1, "text": "Option 1", "isHidden": 0 }, { "id": 2, "text": "Option 2", "isHidden": 1 }, { "id": 3, "text": "Option 3", "isHidden": 0 }]}; U ...

Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2. function recursionFib(num){ if(num ...

Guide on utilizing map function in JavaScript and Vue to generate a fresh array

I am working on implementing a map method in JavaScript and Vue to generate a new array of objects while only including specific items in each object. I have designed a user interface with 2 checkboxes corresponding to 2 distinct objects: <div v-for ...

Discover the best method for transferring MySQL data between pages

Can anyone help guide me in the right direction on how to allow a user to click a link within a PHP While Loop generated MySQL table and pass that data to another page? I've searched through similar questions but haven't found a solution that fit ...

Capture the selected hyperlink and show the corresponding page title in a designated box for reference

I want to track the links that users click on and display them in a box with an image and name of the page. Additionally, I would like to show how long the user spent on each page below the image. The images in the box should also be clickable links to the ...

Menu secured in place within the wrapper

My website is contained in a wrapper with a max width, and I have a fixed side menu that can be toggled with a button. The problem I am facing is keeping the fixed side menu within the page wrapper. Fixed elements are typically positioned relative to the ...

Show the current Date and Time dynamically using only one line of JavaScript code

After running this command, I encountered an issue: $("#dateTime").text(new Date().toLocaleString()); The result displayed was 2/21/2020, 10:29:14 AM To make the time increase every second, I attempted this code: setInterval($("#dateTime").text(new Dat ...

Using $nin alongside $and in Mongoose

Implementing a filter for an admin user using mongoose operations. The user should be able to view all saved files except for those that are classified as draft files. However, the admin user should still have access to their own saved draft files. Code ...

Refreshing a div by replacing its content with text entered into an input field

I'm exploring React and attempting to create a basic div that dynamically changes its text based on input from an input box. Below is the code I have written so far: import React from "react"; import ReactDOM from "react-dom"; const rootElement = d ...