Toggle Visibility in Vue

Oct 5, 2022

To conditionally display content on your Vue applications, you can use the v-show directive. The v-show directive toggles the display css property of the element.

const app = Vue.createApp({
  data: () => ({ display: true }),
  methods: {
    toggleText() {
      this.display = !this.display;
    }
  },
  template: `
  <div>
    <h1 v-show="display">Hello!</h1>
    <button @click="toggleText()">Toggle</button>
  </div>
  `
}).mount('#content');

Using v-bind:class

The v-show directive works well for most cases. But if you want more fine-grained control over the CSS of how the element is hidden, like hiding the element using height: 0px; or opacity: 0;, you can use v-bind:class to conditionally add a class to your element.

.hide {
  display: none;
}
const example = Vue.createApp({
  data: () => ({ hide: true }),
  methods: {
    toggleText() {
      this.hide = !this.hide;
    }
  },
  template: `
  <div>
    <h1 v-bind:class="{hide:hide}">Hello!</h1>
    <button @click="toggleText()">Toggle</button>
  </div>
  `
}).mount('#example');

Using v-if

The v-if directive is similar to v-show. The major difference is that v-if unmounts the element from the DOM, while v-show simply hides it.

const example1 = Vue.createApp({
  data: () => ({ display: true }),
  methods: {
    toggleText() {
      this.display = !this.display;
    }
  },
  template: `
  <div>
    <h1 v-if="display">Hello!</h1>
    <button @click="toggleText()">Toggle</button>
  </div>
  `
}).mount('#example1');

Keep in mind that v-if will fire the Vue mounted hooks of any component underneath the v-if when the v-if expression changes from false to true.


Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials