vue中v-on的使用,引數,修飾符
阿新 • • 發佈:2020-10-22
v-on繫結事件監聽,簡寫為@(語法糖)
v-on繫結點選時間實現資料增減的小例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> h2 { display: inline; margin: 20px; }</style> </head> <body> <div id="app"> <!-- button繫結點選事件 increasement 不需要傳參可以不加() --> <button @click = 'incresement'>+</button> <h2>{{counter}}</h2> <button @click = 'decresement'>-</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const app= new Vue({ el : '#app', data : { counter : 0 //定義計數器 }, methods : { //定義增加和減少時呼叫的函式 可以省略:function incresement:function(){ this.counter++; }, decresement(){this.counter--; } } }) </script> </body> </html>
含有形參的函式繫結事件時,加()和不加()的區別
函式本身不需要引數時,可直接省略()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <!-- 按鈕1 2 繫結相同事件btn1 btn2,被繫結事件包含形參 button1繫結點選事件加(),但不傳實參,預設為undefined button2不加(),預設傳入原生事件 MouseEvent{isTrusted: true....} --> <button @click = 'btn1()'>button1</button> <button @click = 'btn2'>button2</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { msg :'hello' }, methods: { btn1(arg){ console.log(arg); }, btn2(arg){ console.log(arg); } } }) </script> </body> </html>
同時需要普通引數和event的時候,需要通過$event傳遞實參
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <button @click ='btn3(123,$event)' >button3</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { msg :'hello' }, methods: { btn3(arg,event){ console.log(arg,event); } } }) </script> </body> </html>
.stop - 阻止事件冒泡
.prevent - 阻止預設行為
.native - 監聽元件根元素的原生事件。
.once - 只觸發一次回撥