Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  76] [ 6]  / answers: 1 / hits: 24048  / 8 Years ago, mon, december 19, 2016, 12:00:00

I am learning Vuejs and I am constantly finding simple things like removing a class to be a pain. Please tell me how I can allow the .active class to be added or removed based on clicks between the 3 links.



In the example below the adding is working fine but it adds .active to all the links, and does not remove when clicked on again.



<div id=app>
<h2>App</h2>
<ul>
<li><a href=# class=link :class={ active: isActive } @click=activeLink>Link text</a></li>
<li><a href=# class=link :class={ active: isActive } @click=activeLink>Link text</a></li>
<li><a href=# class=link :class={ active: isActive } @click=activeLink>Link text</a></li>
</ul>
</div>


JS



var app = new Vue({
el: '#app',
data: {
isActive: false
},
methods: {
activeLink() {
// the line below did not work
// document.getElementsByClassName(active).isActive = false,
this.isActive = true
}
}
})


JSfiddle is here, https://jsfiddle.net/s9r4q0gc/


More From » vuejs2

 Answers
8

You need to catch the event handler in the method and using that you can refer to the callee i.e. anchor object in this case.



See the fiddle : https://jsfiddle.net/s9r4q0gc/2/



activeLink(event) {
if(event.target.className == noclass)
{
event.target.className = link active;
}
else
{
event.target.className = noclass;
}
}


UPDATED:



May be try this fiddle and see if it is hitting the bulls eye : https://jsfiddle.net/s9r4q0gc/4/



  var app = new Vue({
el: '#app',
data: {
isActive: false
},
methods: {
activeLink(event) {
var checkboxes = document.getElementsByClassName (noclass);

for (var i=0; i<checkboxes.length; i++) {
checkboxes[i].className = link active;
//checkboxes[i].className = link;
}
event.target.className = noclass;
}
}
})

[#59646] Saturday, December 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adrienb

Total Points: 500
Total Questions: 104
Total Answers: 104

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
;