v-on监听 DOM 事件,并在触发时运行一些 JavaScript 代码。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 开发环境版本 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button v-on:click="counter += 1">Add 1</button> <p>The button above has been clicked {{ counter }} times.</p> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { counter:0 } }) </script> </html>
效果:
然而许多事件处理逻辑会更为复杂,所以直接把 JavaScript 代码写在v-on
指令中是不可行的。因此v-on
还可以接收一个需要调用的方法名称
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 开发环境版本 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button v-on:click="add">Add 1</button> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { counter:0 }, methods:{ add:function(){ counter+=1 alert(this.counter) } } }) </script> </html>
事务处理方法传递参数
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 开发环境版本 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button v-on:click="addnum(counter)">Add {{counter}}</button> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { counter:1 }, methods:{ addnum:function(num){ this.counter = num+this.counter alert(this.counter) } } }) </script> </html>
注意:v-on的简写 @