How can I hide an element with Vue.js when it is clicked? There's only one element to hide.
A jQuery solution would look like that:
$('.button').click(function() {
$('.hideme').hide();
);
But what is the Vue.js equivalent of this?
First of all jQuery works out of the box. This is one main difference. So you have to initialize your Vue Component or App. You are binding that component with its data to one specific HTML tag inside your template. In this example the specified element is <div id="app"></div>
and is targeted through el: #app
. This you will know from jQuery.
After that you declare some variable that holds the toggle state. In this case it is isHidden
. The initial state is false
and has to be declared inside the data
object.
The rest is Vue-specific code like v-on:click=""
and v-if=""
. For better understand please read the documentation of Vue:
I am recommening you to read in this order if you want to get a quick overview. But please consider reading the whole or at least longer parts of the documentation for better understanding.
var app = new Vue({
el: '#app',
data: {
isHidden: false
}
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<button v-on:click="isHidden = true">Hide the text below</button>
<button v-on:click="isHidden = !isHidden">Toggle hide and show</button>
<h1 v-if="!isHidden">Hide me on click event!</h1>
</div>