<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Vue方法与事件</title> <meta content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://www.jb51.net/js/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div> <button @click="sayHi">点击我</button> <!--这里使用@--> </div> <script type="text/javascript"> var myVue = new Vue({ el: '#test', methods: { //这里使用methods sayHi: function () { alert('我被点击了') } } }) </script> </body> </html>
二 方法传参
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Vue方法与事件</title> <meta content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://www.jb51.net/js/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div> <button @click="sayHi('你好')">说你好</button> <!--这里使用@--> <button @click="sayHi('我被点击了')">说我被点击了</button> <!--这里使用@--> </div> <script type="text/javascript"> var myVue = new Vue({ el: '#test', methods: { //这里使用methods sayHi: function (message) { alert(message) } } }) </script> </body> </html>
三 vue访问原生 DOM 事件
注意用$event获取
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Vue方法与事件</title> <meta content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://www.jb51.net/js/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div> <button @click="changeColor('你好',$event)">点击我</button> <!--这里使用@--> <div @mouseover="over('鼠标从我上面滑过',$event)"> 鼠标从我上面滑过试试 </div> </div> <script type="text/javascript"> var myVue = new Vue({ el: '#test', methods: { //这里使用methods changeColor: function (message, event) { alert(message+event); //弹出我被点击了,事件是[object MouseEvent] }, over :function (message, event) { alert(message+event); //弹出鼠标从我上面滑过,事件是[object MouseEvent] } } }) </script> </body> </html>
四 事件修饰符
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Vue方法与事件</title> <meta content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://www.jb51.net/js/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div> <button @click.stop="sayHi('你好')">说你好</button> <!-- 阻止单击事件冒泡 --> <button @click.prevent="sayHi('你好')">说你好</button> <!-- 提交事件不再重载页面 --> <button @click.stop.prevent="sayHi('你好')">说你好</button> <!-- 阻止单击事件冒泡和提交事件不再重载页面 --> <button @click.capture="sayHi('你好')">说你好</button> <!-- 添加事件侦听器时使用 capture 模式 --> <button @click.self="sayHi('你好')">说你好</button> <!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 --> <div @keyup.13="sayHi('你好')">说你好</div> <!-- 只有在 keyCode 是 13 时调用 vm.submit() --> </div> <script type="text/javascript"> var myVue = new Vue({ el: '#test', methods: { //这里使用methods sayHi: function (message) { alert(message) } } }) </script> </body> </html>