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

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

Why does Material-UI TableCell-root include a padding-right of 40px?

I'm intrigued by the reasoning behind this. I'm considering overriding it, but I want to ensure that I'm not undoing someone's hard work. .MuiTableCell-root { display: table-cell; padding: 14px 40px 14px 16px; font-size: 0. ...

"Revamping the text style of input materials in React JS: A step-by

How can I modify the style of the text field component in Material UI? Specifically, I would like to change the appearance of the text that the user enters. I have attempted to use the Material API, but it has not provided the desired results. Here is an ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

Transforming Node's loops into asynchronous functions

I have the following sync function: for (var i = 0; i < results.length; i++) { var key1 = results[i]['__key']; for (var j = i + 1; j < results.length; j++) { ...

What is the best way to pass the "$user" variable in a loadable file using ajax?

Is there a way to send the variable user to the mLoad.php file before executing this script? Any suggestions would be greatly appreciated. Thank you! $(document).ready(function(){ $("#message_area").load('mLoad.php'); $("#userArea").submit(func ...

The functionality to generate forms on the click of a button appears to be malfunctioning

I am currently attempting to dynamically create Bootstrap Panels using an `onclick` function. However, I want each Panel to generate multiple forms when the button is clicked. In my current code, the first Panel successfully creates forms when the button i ...

The function of jQuery .click() not triggering on elements within msDropDown

I'm having difficulty implementing jQuery on an Adobe Business Catalyst site. The HTML snippet below shows the structure: <div class="banner-main"> <div class="banner-top"> <section class="banner"> <div class="catProd ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

Is there a way to showcase various category._id within a single page route using Vue.js?

When trying to display multiple categories under a route, clicking on the first category shows the products. However, when clicking on another category, the products do not show up unless I hard refresh the page, which then displays the list of products un ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

JavaScript Error - Value Not Assigned

I'm having trouble formatting a graph in my code. I keep encountering an undefined error when using console.log to output the data. Here's the snippet of my code: $(document).ready(function () { var graphData = new Array(); $.getJSON("ds ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

The issue with ng-change is causing the previously selected drop down option to be cleared

After successfully implementing live searching with ng-change, I encountered an issue with a pre-selected drop-down box. Despite setting the selected="selected" attribute to make option three the default selection, the drop-down box jumps to the top optio ...

What is the reasoning behind having two separate permission dialog boxes for accessing the webcam and microphone in flash?

I am currently using a JavaScript plugin known as cameratag () in order to record videos through the web browser. This plugin utilizes a flash-based solution. When the flash application requests permission to access the webcam, it presents a security dialo ...

Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trig ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...