1. 在Vue中可以使用v-on来监听事件
v-on:click="函数/表达式"
简写: @click =“函数/表达式”
-
案例01:直接调用foo函数
<div id="app"> <button @click="foo">Register Events</button> </div> <script> var vm = new Vue({ el: "#app", data: { }, methods: { foo(e) { console.log(e.target.textContent);//输出Register Events } } }) </script>
-
案例02:给bar函数传参
<div id="app"> <button @click="bar('Hello Event')">Register Events</button> </div> <script> var vm = new Vue({ el: "#app", data: { }, methods: { bar(val) { console.log(val);//输出 Hello Event } } }) </script>
-
案例3 :可以调用$event事件对象形参
<div id="app"> <button @click="bar('Hello',$event)">Register Events</button> </div> <script> var vm = new Vue({ el: "#app", data: { }, methods: { bar(val, e) { console.log(val, e.target.innerHTML); } } }) </script>
2.事件修饰符
-
阻止事件默认行为(prevent)
<div id="app"> <a href="http://www.baidu.com" @click.prevent="bar"> 百度 </a> </div> <script> var vm = new Vue({ el: "#app", data: {}, methods: { bar() { console.log("阻止事件默认行为"); } } }) </script>
-
阻止事件冒泡(stop)
<div id="app"> <div class="box1" @click="bar"> <div class="box2" @click.stop="foo"></div> </div> </div> <script> var vm = new Vue({ el: "#app", data: {}, methods: { bar() { console.log("外面盒子事件"); }, foo() { console.log("里面盒子事件"); } } }) </script>
-