[Vue.js] Toggle (Show/Hide) HTML Element


Learn to toggle (Show/Hide) HTML DOM element is my favorite exercise for using a new JavaScript framework/library or compile-to-JavaScript languages such as GopherJS.

Demo

The following is key points in the code:

  • Use boolean variable isShow to control the visibility of DOM element.
  • When users click on the element with class name control (line 15~17), isShow = !isShow expression will make isShow become true if it is false, become false if it is true.
  • The element with class name content (line 18) will display or disappear by v-show directive and true/false of isShow.
index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue.js Toggle (Show/Hide) DOM Element Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    .control:hover {cursor: pointer;}
    .content {width: 200px; height: 200px; background: yellow;}
  </style>
</head>
<body>

<div id="app">
  <div v-on:click="isShow = !isShow" class="control">
    click me to toggle (show/hide) HTML element
  </div>
  <div v-show="isShow"  class="content">contents</div>
</div>

<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<script>
  new Vue({
    el: '#app',
    data: {
      isShow: false
    }
  })
</script>
</body>
</html>

Tested on:

  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
  • Vue.js 2.1.10.

References:

[1]Event Handling — Vue.js