003_Vue事件
1. Vue如何處理事件?
1.1. v-on指令用法
<input type='button' v-on:click='num++' />1.2. v-on簡寫形式
<input type='button' @click='num++' />2. 事件函數(shù)的調(diào)用方式
2.1. 直接綁定函數(shù)名稱
<input type='button' @:click='handle1' />2.2. 調(diào)用函數(shù)
<input type='button' @:click='handle1()' />3. 事件函數(shù)參數(shù)傳遞
3.1. 普通參數(shù)和事件對象
<input type='button' @:click='handle1($event)' /> <input type='button' @:click='handle2(500, $event)' />3.2. 如果事件直接綁定函數(shù)名稱, 那么默認(rèn)會傳遞事件對象作為事件函數(shù)的第一個參數(shù)。
3.3. 如果事件綁定函數(shù)調(diào)用, 那么事件對象必須作為最后一個參數(shù)傳遞, 并且事件對象的名稱必須是$event。
4. 點擊事件案例
4.1. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>點擊事件</title></head><body><div id="app"><div>{{num}}</div><div><button v-on:click="++num">點擊1</button><button @click="++num">點擊2</button><!-- 1. 如果事件直接綁定函數(shù)名稱, 那么默認(rèn)會傳遞事件對象作為事件函數(shù)的第一個參數(shù)。 --><!-- 2. 如果事件綁定函數(shù)調(diào)用, 那么事件對象必須作為最后一個參數(shù)傳遞, 并且事件對象的名稱必須是$event。 --><button @click="handle1">點擊3</button><button @click="handle1($event)">點擊4</button><button @click="handle2(500, $event)">點擊5</button></div></div><script type="text/javascript" src="vue.min.js"></script><script type="text/javascript">var vm = new Vue({el: "#app",data: {num: 0,},methods: {handle1: function(event){++this.num;console.log(event.target.innerHTML);},handle2: function(p, event){++this.num;this.num += p;console.log(event.target.innerHTML);}}});</script></body> </html>4.2. 運行效果
4.3. 點擊1?
4.4. 點擊2?
4.5. 點擊3
4.6. 點擊4?
4.7. 點擊5?
?
9. 事件修飾符-阻止冒泡
9.1. .stop阻止冒泡。
9.2. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>事件-阻止冒泡.stop</title></head><body><div id="app"><div>{{num}}</div><div @click="handle1"><button @click.stop="handle2">點擊1</button></div></div><script type="text/javascript" src="vue.min.js"></script><script type="text/javascript">var vm = new Vue({el: "#app",data: {num: 0,},methods: {handle1: function(event){++this.num;console.log('handle1: ' + event.target.innerHTML);},handle2: function(event){console.log('handle2: ' + event.target.innerHTML);// js默認(rèn)的阻止冒泡函數(shù)// event.stopPropagation();}}});</script></body> </html>9.3. 運行效果
10. 事件修飾符-阻止默認(rèn)行為
10.1. .prevent阻止默認(rèn)行為
10.2. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>事件-阻止默認(rèn)行為.prevent</title></head><body><div id="app"><a href="http://www.baidu.com" @click.prevent="handle1">百度</a></div><script type="text/javascript" src="vue.min.js"></script><script type="text/javascript">var vm = new Vue({el: "#app",data: {},methods: {handle1: function(event){// js默認(rèn)的阻止默認(rèn)行為函數(shù)// event.preventDefault();}}});</script></body> </html>10.3. 運行效果, 點擊超鏈接不跳轉(zhuǎn)
總結(jié)
- 上一篇: 002_Vue指令
- 下一篇: 004_Vue按键修饰符