背景:
在一些搜索框中,我们往往需要监听键盘的按下(onkeydown)
或抬起(onkeyup)
事件以进行一些操作。在原生js
或者jQuery
中,我们需要判断e.keyCode
的值来获取用户所按的键。这样就存在一个问题:我们必须知道某个按键的keyCode
值才能完成匹配,使用起来十分不便。
方案:
在Vue
中,已经为常用的按键设置了别名,这样我们就无需再去匹配keyCode
,直接使用别名就能监听按键的事件。
<input @keyup.enter="function">
另外,Vue
中还支持组合写法:
注意
但是,如果是在自己封装的组件或者是使用一些第三方的UI
库时,会发现并不起效果,这时就需要用到.native
修饰符了,如:
<el-input
v-model="inputName"
placeholder="搜索你的文件"
@keyup.enter.native="searchFile(params)"
>
</el-input>
如果遇到.native
修饰符也无效的情况,可能就需要用到$listeners
了,具体用法请参考Vue
官方文档:将原生事件绑定到组件。
另外:
//自定义键盘事件
Vue.directive('on').keyCodes.ctrl=17;
例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>键盘事件</title>
<script src="js/vue.js"></script>
<script>
//自定义键盘事件
Vue.directive('on').keyCodes.ctrl=17;
window.onload=function(){
var vm=new Vue({
el:'#wrap',
data:{
},
methods:{
show:function(e){
// console.log(111);
// console.log(e.keyCode); //按钮的code值,ASCII码
//判断是否按下回车
/*if(e.keyCode==13){
console.log('您按下回车');
}*/
console.log(111);
}
}
});
};
</script>
</head>
<body>
<div id="wrap">
<!-- 用户名:<input type="text" @keydown="show($event)"> -->
<!-- 简化按键的判断 -->
<!-- 用户名:<input type="text" @keydown.13="show($event)"> -->
<!-- 用户名:<input type="text" @keydown.enter="show($event)"> -->
<!-- 用户名:<input type="text" @keydown.delete="show($event)"> -->
<!-- 用户名:<input type="text" @keydown.x="show($event)"> -->
用户名:<input type="text" @keydown.ctrl="show($event)">
</div>
</body>
</html>