SoFunction
Updated on 2025-04-11

Detailed explanation of event binding and method of vue

1. In vue, bind events and use v-on: event type. If you bind a click event, we can do this

 = function () {
     var c = new Vue({
       el : 'body',
       methods : {
        say : function(){
          alert( 'Welcome to learn vue' );
        }
       }
     });
    }

<input type="button" value="Click me" v-on:click="say();"/>

To add a method, you need to add a method configuration in the object parameters of the vue instance. methods are literal methods. As in the above example, we added a say method, which binds a click event in the button. When the event is triggered, execute say();

2. Bind the double-click event and operate the data in data through the functions defined in the methods method.

 = function () {
     var c = new Vue({
       el : 'body',
       data : {
         arr : [ 10, 20, 30 ]
       },
       methods : {
        change : function(){
          ( 40 );
        }
       }
     });
    }

    <input type="button" value="Click me" v-on:dblclick="change();"/>
    <ul >
      <li v-for="value in arr">{{value}}</li>
    </ul>

In the above example, by binding a double-click event in the button, when the event is triggered, the change method is called, and the array arr defined in data is accessed, and the value of push is 40 to the arr, then the arr data in data is modified. Based on the fact that vue is MVVM driver, the modification of arr will be updated to the view in real time. The result is that a new li is added under ul, with a value of 40.

3. Directive: v-show, the value is false/true. When false, the element is hidden, and when true, the element is displayed.

<style>
    div {
      width: 200px;
      height: 200px;
      background: red;
      float:left;
      margin:20px;
    }
  </style>
  <script src="../js/"></script>
  <script>
     = function () {
     var c = new Vue({
       el : 'body',
       
     });
    }
  </script>

 <div v-show="true"></div>
 <div v-show="true"></div>
 <div v-show="false"></div>


Output result:

<div></div>
<div></div>
<div style="display: none;"></div>

4. Click the button to realize div display and hide

&lt;style&gt;
    div {
      width: 200px;
      height: 200px;
      background: red;
    }
  &lt;/style&gt;
  &lt;script src="../js/"&gt;&lt;/script&gt;
  &lt;script&gt;
     = function () {
      var c = new Vue({
        el: 'body',
        data: {
          flag: false
        },
        methods : {
          toggle : function(){
             = !;
          }
        }
      });
    }

&lt;input type="button" value="Click me" v-on:click="toggle();"/&gt;
&lt;div v-show="flag"&gt;&lt;/div&gt;

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.