Clinton Green Clinton Green - 1 day ago 4
Javascript Question

Vue js - Getting Methods to work in Components

I have a component that passes in data, then I need to change that data from true to false on click. I have created a method called

toggleClass
for that but it's not working, and I am not getting any errors.

Vue.component('moustache', {
name: 'moustache',
props: ['type', 'img'],
template: `<li>
<p><strong>@{{ type }}</strong></p>
<img width="300" height="200" src="/img/image.jpg">
<button class="btn btn-primary" v-bind:class="{ active: isActive }" :data-type="type" @click="toggleClass">Vote</button>
</li>`,
data: function(){
return{
isActive: false
}
},
methods: {
toggleClass(){
isActive: true
}
}
});

new Vue({
el: '#app'
});

Answer

You need to use this so that you can access the component properies:

toggleClass(){
     this.isActive = !this.isActive;
}
Comments