Liga
Liga

Reputation: 3439

Vue.js - change color for all elements except the element clicked

I am trying to switch from jQuery to Vue.js and I am a little bit stuck with this. I have 3 buttons on the page. When I click on a button, I want all the other buttons to change the background color to green and the button that was clicked - change it's color to black.

It was just 2 lines of code with jQuery but I can't figure out how to accomplish it with Vue.js. There also doesn't seem to be a this keyword for Vue.js.

Also, at this point, I'd like to just apply raw css background-color property instead of applying a class.

Here is my jQuery code - very simple

<div class="main-content-area">    
  <div class="btn">Click me!</div>
  <div class="btn">Click me!</div>
  <div class="btn">Click me!</div>    
</div>
const Example = new Vue({
  el: '.main-content-area',
  methods: {
    addEventListeners() {
      $(document).ready(function() {
        $(".btn").click(function() {
          $(".btn").css("background-color", "green"); // Make all buttons green
          $(this).css("background-color", "black"); // Make the clicked button black
        });
      });
    }
  },
  mounted: function() {
    this.addEventListeners();
  }
})

With Vue.js - I got only this far...

<div class="main-content-area">    
  <div class="btn" @click="changeColor">Click me!</div>
  <div class="btn" @click="changeColor">Click me!</div>
  <div class="btn" @click="changeColor">Click me!</div>    
</div>
const Example = new Vue({
  el: '.main-content-area',
  methods: {
    changeColor() {
      //  Change color to green for all .btn elements
      //  and change  color for clicked .btn to black
    }
  })

Upvotes: 4

Views: 9609

Answers (2)

Archeg
Archeg

Reputation: 8462

This is a better approach, without using unsafe $root and $children.

<template>
  <div class="hello">
    <button class="btn" @click="activeButton = 0" v-bind:style="{'background-color':buttonColor[0]}">Click me!</button>
    <button class="btn" @click="activeButton = 1" v-bind:style="{'background-color':buttonColor[1]}">Click me!</button>
    <button class="btn" @click="activeButton = 2" v-bind:style="{'background-color':buttonColor[2]}">Click me!</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      activeButton: 0
    };
  },
  computed: { 
    buttonColor: function() {
      let result = [];
      for (var i = 0; i< 3; i++){
        if (this.activeButton == i){
          result.push('black');
        } else {
          result.push('green');
        }
      }

      return result;
    }
  }
};
</script>

Demo: https://codesandbox.io/s/8kz9y0rjj9

You could also wrap button in a separate component, as @Zoha suggested, but given that you did not ask for it, I did not do that. This would allow to hide buttonColor implementation in the component.

Also please note that using classes is much preferable and cleaner approach: No need for ugly buttonColor computed function.

<template>
  <div class="hello">
    <button class="btn" @click="activeButton = 0" v-bind:class="{'greenBtn':true, 'blackBtn': activeButton == 0}">Click me!</button>
    <button class="btn" @click="activeButton = 1" v-bind:class="{'greenBtn':true, 'blackBtn': activeButton == 1}">Click me!</button>
    <button class="btn" @click="activeButton = 2" v-bind:class="{'greenBtn':true, 'blackBtn': activeButton == 2}">Click me!</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      activeButton: 0
    };
  },
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
 .greenBtn {
   background-color: green
 }

 .blackBtn {
   background-color: black
 }
</style>

Upvotes: 1

Zoha
Zoha

Reputation: 586

use component for buttons :

HTML :

<div class="main-content-area">

    <my-custom-button component-type="my-custom-button" ></my-custom-button>
    <my-custom-button component-type="my-custom-button"></my-custom-button>
    <my-custom-button component-type="my-custom-button"></my-custom-button>

</div>

JavaScript :

Vue.component("my-custom-button",{
        template : '<div class="btn" :style="buttonStyles" @click="activeThisButton" >Click me!</div>',

    data(){
        return {
        isActive : false,
      }
    },

    computed : {
        buttonStyles(){
        return {
            backgroundColor : this.isActive  ? 'green' : '',
        }
      }
    },

    methods : {
        activeThisButton(){
        // call inactiveAllButtons on parent to deselect all buttons
        this.$root.inactiveAllButtons();
        // active current button
        this.isActive = true;
      }
    }
})

const Example = new Vue
({

    el: '.main-content-area',

    methods : {
        // filter children and find buttons ( by component-type property )
        // and inactive all .
        inactiveAllButtons(){
        var buttons = this.$children.filter(function(child) {
            return child.$attrs['component-type'] === 'my-custom-button';
        });
        for(var i = 0 ; i < buttons.length ; i++ ){
          buttons[i].isActive = false;
        }
      }
    }

});

jsfiddle demo

Upvotes: 1

Related Questions