Asked By: Anonymous
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
}
})
Solution
Answered By: Anonymous
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;
}
}
}
});