(1)使用v-on指令能够添加事件监听,语法:
v-on:eventName="fn" 也能够简写成 @eventName="fn"
(2)回调函数的参数:$event就是当前触发事件的元素,即便不传$event,在回调函数中也能够使用event这个参数vue
基本使用:app
<div id="app"> <button v-on:click="test">点我</button> <button v-on:click="test2('hello vue')">点我2</button> <button v-on:click="test3($event)">点我3</button> <button v-on:click="test4">点我4</button> </div>
methods: { test() { console.log('hi'); }, test2(content) { console.log(content); }, test3(event) { console.log(event.target); }, test4(){ //即便不传$event,在回调函数中也能够使用event这个参数 console.log(event.target.innerText); } }
其余事件:函数
<body> <div id="app"> <!-- 点击事件 --> <button @click="testClick">点我</button> <!-- input事件 --> <input type="text" @input="testInput"> <!-- change事件 --> <select @change="testChange"> <option value="020">广州</option> <option value="021">上海</option> </select> </div> </body> <script> new Vue({ el:"#app", data:{}, methods:{ testClick(){ console.log('Click') }, testInput(){ console.log('Input') }, testChange(){ console.log('Change') } } }) </script>
事件修饰符用来控制事件的冒泡和默认行为,共有2个:
.stop:阻止事件冒泡
.prevent:阻止默认事件spa
基本使用:code
<!-- 阻止事件冒泡 --> <div id="big" @click="test"> <div id="small" @click.stop="test2"></div> </div> <!-- 阻止默认事件,点击a连接不会发生跳转,只会执行test方法的代码 --> <a href="https://www.baidu.com/" @click.prevent="test">百度一下</a>
按键修饰符用来监听某个按键是否被按下事件
使用@keyup指令能够为元素添加键盘事件,例如:ip
<!-- 任何按键按下都会触发回调函数 --> <textarea @keyup="testKeyup" cols="30" rows="10"></textarea>
若是咱们想在特定按键按下才触发回调的话就添加按键修饰符或按键码,例如:
语法: @keyup.按键修饰符=回调函数
语法: @keyup.按键码=回调函数get
<!-- 只有回车键按下的时候才会触发回调函数 --> <!-- 下面的两种写法效果是一致的 --> <!--使用按键码,回车键的keyCode是13 --> <textarea @keyup.13="testKeyup" cols="30" rows="10"></textarea> <!--使用按键修饰符,由于回车键比较经常使用,因此vue为他设置了名称,能够直接使用enter来代替。 --> <textarea @keyup.enter="testKeyup" cols="30" rows="10"></textarea>
methods: { testKeyup() { console.log('回车键被按下了'); } }
Vue 提供了绝大多数经常使用的键修饰符:input
其他按键能够用按键码回调函数
<!--q的keyCode是81,当按下q键时会触发test方法 --> <input type="text" value="hello" @keyup.81="test">
你能够经过全局 Vue.config.keyCodes.自定义按键修饰=按键码,来自定义按键修饰符,例如:
//q的keyCode是81 <input type="text" value="hello" @keyup.q="test"> Vue.config.keyCodes.q=81