Sometimes, we want to invert boolean inline on click with Vue.js and JavaScript.
In this article, we’ll look at how to invert boolean inline on click with Vue.js and JavaScript.
How to invert boolean inline on click with Vue.js and JavaScript?
To invert boolean inline on click with Vue.js and JavaScript, we can set the @click
directive to a statement to toggle the boolean.
For instance, we write:
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id='app'>
</div>
to add the Vue script and app container.
Then we write:
const v = new Vue({
el: '#app',
template: `
<div>
<button @click='toggle = !toggle'>
{{ toggle ? 'show' : 'hide' }}
</button>
</div>
`,
data: {
toggle: true
},
})
to set @click
to toggle = !toggle
to toggle the toggle
reactive property.
And we display show' if
toggleis
true` and ‘hide’ otherwise.
Therefore, when we click the button, we see the button text switch between ‘show’ and ‘hide’.
Conclusion
To invert boolean inline on click with Vue.js and JavaScript, we can set the @click
directive to a statement to toggle the boolean.