Vue event handling

Previous remarks

The way Vue events are monitored seems to run counter to the traditional idea of separation of concerns. In fact, all Vue.js event handling methods and expressions are strictly bound to the ViewModel of the current view, which does not cause maintenance difficulties. Using v-on has the following advantages:

1. Glancing at HTML template can easily locate the corresponding method in JS code.

2. Without having to manually bind events in JS, ViewModel code can be very pure logic, completely decoupled from DOM, and easier to test.

3. When a ViewModel is destroyed, all event handlers are automatically deleted. You don't have to worry about cleaning them up by yourself.

This article describes Vue event handling in detail

 

event listeners

Binding event listeners with v-on instructions

<div id="example">
  <button v-on: click= "counter += 1">Add 1</button>
  <p> This button has been clicked {counter} times. </p>
</div>
<script>
var example = new Vue({
  el: '#example',
  data: {
    counter: 0
  }
})
</script>

[Method]

Many event handling logic is complex, so it is sometimes not feasible to write JS code directly in v-on instructions. The v-on instruction can receive a defined method call

[Note] The arrow function should not be used to define the methods function, because the arrow function binds the context of the parent scope, so this will not point to the Vue instance as expected

<div id="example">
   <button v-on:click="num">Test button</button>
   <p>{{message}}</p>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    counter:0,
    message:''
  },
  methods: {
    num: function (event) {
      if (event) {
        this.message = event.target.innerHTML + 'Pressed' + ++this.counter + 'second';
      }
    }
  }
})
</script>

[Inline statement]

In addition to directly binding to a method, you can also use inline JS statements

<div id="example">
  <button v-on:click="say('hi')">Say hi</button>
  <button v-on:click="say('what')">Say what</button>
   <p>{{message}}</p>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    message:''
  },
  methods: {
    say: function (message) {this.message = message;}
  }
})
</script>

Sometimes native DOM events need to be accessed in the inline statement processor. It can be passed into the method with a special variable $event.

<div id="example">
  <button v-on:click="say('hi',$event)">Say hi</button>
  <button v-on:click="say('what',$event)">Say what</button>
   <p>{{message}}</p>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    message:''
  },
  methods: {
    say: function (message,event) {
      if(event){
        event.preventDefault();
      }  
      this.message = message;
    }
  }
})
</script>

 

Event modifier

Calling event.preventDefault() or event.stopPropagation() in event handlers is a very common requirement. Although this can be easily done in methods, it's a better way: methods only have pure data logic, rather than dealing with DOM event details.

To solve this problem, Vue.js provides event modifiers for v-on. Call modifiers by instruction suffixes represented by dots (.)

stop stops bubbles
prevent prevents default events
Capture uses event capture mode
self triggers only on the current element itself
Once triggers only once

Here are some examples

<! - Prevent click event bubbles - >
<a v-on:click.stop="doThis"></a>
<! - Submit events no longer overload Pages - >
<form v-on:submit.prevent="onSubmit"></form>
<! - Modifiers can be concatenated - >
<a v-on:click.stop.prevent="doThat"></a>
<! - Only modifiers - >
<form v-on:submit.prevent></form>
<! - Use event capture mode when adding event listeners - >
<div v-on:click.capture="doThis">...</div>
<! - Triggers a callback only when the event triggers the element itself (e.g., not a child element)-->
<div v-on:click.self="doThat">...</div>
<! - The click event will only trigger once - >
<a v-on:click.once="doThis"></a>

[Note] When using modifiers, order is important; the corresponding code will be generated in the same order. Therefore, using @click.prevent.self will block all clicks, while @click.self.prevent will only block clicks on elements.

[stop]

Prevent bubbles

<div id="example" @click="setVal1" style="border:1px solid black;width:300px;">
  <button @click="setVal">Ordinary button</button>
  <button @click.stop="setVal">Prevent bubbles</button>
  <button @click="reset">reduction</button>
  <div>{{result}}</div>
</div>
<script>var example = new Vue({
  el: '#example',
  data:{
    result:''
  },
  methods:{
    setVal(event){
      this.result+=' Sub level ';
    },
    setVal1(){
      this.result+=' Father level ';
    },
    reset(){
      history.go()
    }
  }
})
</script>

[prevent]

Cancel default events

<div id="example">
  <a href="http://cnblogs.com" target="_blank">Ordinary links</a>
  <a @click.prevent href="http://cnblogs.com" target="_blank">Cancel default behavior</a>
</div>
<script>
var example = new Vue({
  el: '#example'
})
</script>

[capture]

Event capture mode

<div id="example" @click.capture="setVal1" style="border:1px solid black;width:300px;">
  <button @click.capture="setVal">Event capture</button>
  <button @click="reset">reduction</button>
  <div>{{result}}</div>
</div>
<script>var example = new Vue({
  el: '#example',
  data:{
    result:''
  },
  methods:{
    setVal(event){
      this.result+=' Sub level ';
    },
    setVal1(){
      this.result+=' Father level ';
    },
    reset(){
      history.go()
    }
  }
})
</script>

[self]

<div id="example">
  <div @click="setVal" :style="styleObj1">
    <div :style="styleObj2">ordinary</div>
    <button @click="reset">reduction</button>
  </div>
  <div @click.self="setVal" :style="styleObj1">
    <div :style="styleObj2">self</div>
    <button @click="reset">reduction</button>
  </div>  
</div>
<script>
var styleObj1 = {
  display:'inline-block',
  height:'60px',
  width:'120px',
  'background-color': 'lightblue'
};
var styleObj2 = {
  display:'inline-block',
  height:'30px',
  width:'60px',
  'background-color': 'lightgreen'
};
var example = new Vue({
  el: '#example',
  data:{
    styleObj1:styleObj1,
    styleObj2:styleObj2
  },
  methods:{
    setVal(event){
      event.target.style.outline="solid"
    },
    reset(){
      history.go()
    }
  }
})
</script>

[once]

Triggered only once

<div id="example">
  <button @click="setVal">Ordinary button</button>
  <button @click.once="setVal">Trigger once</button>
  <button @click="reset">reduction</button>
  <div>{{result}}</div>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    result:''
  },
  methods:{
    setVal(event){
      this.result+=' content ';
    },
    reset(){
      history.go()
    }
  }
})
</script>

  

Mouse modifier

These modifiers restrict the handler to listen for specific mouse buttons

Left left key
Right-click.right
middle rollers
<div id="example">
  <button @mouseup.right="right" @mouseup.middle="middle" @mouseup.left="left">{{message}}</button>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    message:'Using left, middle and right keys to click on them will have different effects.'
  },
  methods:{
    left(){
      this.message = 'left'
    },
    right(){
      this.message = 'right'
    },
    middle(){
      this.message = 'middle'
    },        
  }
})
</script>

 

Key modifier

When listening for keyboard events, it is often necessary to monitor common key values. Vue allows key modifiers to be added to v-on when listening for keyboard events

<! - Call vm. submit () --> only if keyCode is 13
<input v-on:keyup.13="submit">

Keeping all keycodes in mind is difficult, so Vue provides aliases for the most commonly used keys:

enter
Tab tab tab key
Delete (capture delete and backspace keys)
esc returns
Space space
up
down
Left left
right
<div id="example">
  <button @keyup.enter="enter" @keyup.tab="tab" @keyup.delete="delete1" @keyup.esc="esc" @keyup.space="space" @keyup.up="up" @keyup.down="down" @keyup.left="left" @keyup.right="right">{{message}}</button>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    message:'After placing the cursor on the button, pressing different keys on the keyboard will have different effects.'
  },
  methods:{
    enter(){
      this.message = 'enter'
    },
    tab(){
      this.message = 'tab'
    },
    delete1(){
      this.message = 'delete'
    }, 
    esc(){
      this.message = 'esc'
    },
    space(){
      this.message = 'space'
    },
    up(){
      this.message = 'up'
    },
    down(){
      this.message = 'down'
    },
    left(){
      this.message = 'left'
    },
    right(){
      this.message = 'right'
    },                 
  }
})
</script>

You can customize key modifier aliases through global config.keyCodes objects

// You can use v-on:keyup.a.
Vue.config.keyCodes.a = 65
<div id="example">
  <button @keyup.a="a"  @keyup.b="b">{{message}}</button>
</div>
<script>
Vue.config.keyCodes.a = 65;
Vue.config.keyCodes.b = 66;
var example = new Vue({
  el: '#example',
  data:{
    message:'Press on the keyboard a Key or b key'
  },
  methods:{
    a(){
      this.message = 'a'
    },
    b(){
      this.message = 'b'
    },    
  }
})
</script>

 

Modifier bond

Mouse or keyboard event monitoring can be activated with the following modifiers to respond when the key is pressed

.ctrl
.alt
.shift
.meta
<!-- Alt + C -->
<input @keyup.alt.67="clear">
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>

The following example

<div id="example">
  <button @click.ctrl="ctrl"  @click.alt="alt"  @click.shift="shift"  @click.meta="meta">{{message}}</button>
</div>
<script>
var example = new Vue({
  el: '#example',
  data:{
    message:'Hold down the auxiliary key separately ctrl,alt,shift,meta Click on it and it will have different effects.'
  },
  methods:{
    ctrl(){
      this.message = 'ctrl'
    },
    alt(){
      this.message = 'alt'
    },
    shift(){
      this.message = 'shift'
    },  
    meta(){
      this.message = 'meta'
    },           
  }
})
</script>

Keywords: Javascript Vue

Added by JBS103 on Thu, 06 Jun 2019 02:54:43 +0300