我正在参加「掘金·启航计划」
事件基本使用
- 使用
v-on:xx或@xx绑定事件,xx是事件名 - 绑定的事件回调需写在
methods对象中,最终呈现在vm(Vue实例)上 methods中配置的函数为一般函数,不能使用箭头函数(this问题)- methods中配置的函数,都是被Vue所管理,this指向vm或组件实例对象
- @click='demo'和@click="demo($event)"效果一致,但后者可以传参
注意📢
事件可以加
()也可不加,事件回调默认有个event对象如果事件中
传递参数则event事件会丢失,此时要使用event则需要传递$event作为参数❗
示例:
<!-- v-on绑定事件 -->
<button v-on:click="showInfo">点击获取信息(不传参)</button>
<!-- v-on简写 -->
<button @click="showInfo2(123,$event)">点击获取信息(传参)</button>
//创建vue实例
var vm = new Vue({
el:'#root',//绑定元素
data:{ //为模板提供数据
msg:'hello Vue!',
},
methods: {
showInfo(e){
console.log(e); //event事件对象
alert('你好不好?')
},
showInfo2(a,event){
console.log(a,event);//123,event事件对象
alert('好得很呐')
}
}
});
事件修饰符
- prevent:阻止默认事件(常用)
- stop:阻止事件冒泡(常用)
- once:事件只触发一次(常用)
- capture:使用事件的捕获模式
- self:只有当
event.targer当前操作元素时才触发事件 - passive:事件的默认行为
立即执行,无需等待事件回调执行完毕
注意:修饰符可以
链式调用(prevent.stop.once....)
<!-- 1. prevent:阻止默认事件 -->
<a href="http://www.baidu.com" @click.prevent="prevent">点我显示信息</a>
<!-- 2. stop:阻止事件冒泡 -->
<div @click="handelBtn" class="btnBox">
<button @click.stop="handelBtn">点我!</button>
</div>
<!-- 3. once:事件只触发一次 -->
<button @click.once="once">点我啊!!</button>
<!-- 4. capture:使用事件的捕获模式 -->
<!--
默认会产生冒泡输出2,1
加上capture使用捕获从外到内输出1,2
-->
<div @click.capture="capture(1)" class="btnBox">
<button @click="capture(2)">快点我!!!</button>
</div>
methods: {
prevent(e) {
// e.preventDefault();
alert('提示信息!')
},
handelBtn(e) {
alert('事件响应btn')
},
once(){
alert('只响应一次!')
},
capture(num){
console.log(num);
}
}
键盘事件
常用按键别名
- 回车:enter
- 删除:delete
- 退出:esc
- 空格:space
- 换行:tab(特殊按键必须配合keydown使用)
- 上:up
- 下:down
- 左:left
- 右:right ...
注意📢
- Vue中未提供别名的键也可以绑定,但多个单词要短横杠命名(caps-lock)
- 系统修饰键用法特殊:
ctrl,alt,shift,win
- 配合keydown可以正常触发(没毛病)
- 配合keyup按下修饰键同时再按下其他键,然后释放其他键,事件才触发❗
- 可以指定系统修饰符搭配使用(ctrl.y)
<!-- 使用按键别名 -->
<input type="text" placeholder="" @keyup.left="showInfo">
<!-- 使用自定义键名 -->
<input type="text" placeholder="" @keyup.hello="showInfo">
<!-- 使用键码(不推荐) -->
<input type="text" placeholder="" @keyup.13="showInfo">
<!-- 指定系统修饰符搭配:ctrl+y -->
<input type="text" placeholder="" @keyup.ctrl.y="showInfo">
Vue.config.keyCodes.hello = 13 //自定义回车键
//配置项。。。
methods: {
showInfo(e){
console.log(e.target.value);//按键抬起触发value值
console.log(e.key,e.keyCode);//按键,键码
}
}