代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>键盘事件</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<h2>欢迎来到{{name}}学习</h2>
<input type="text" placeholder="按下回车键触发事件(输出)" @keyup.enter="showInfo"><br /><br />
<input type="text" placeholder="使用keyCode指定具体的按键(回车键:13)" @keyup.13="showInfo"><br /><br />
<input type="text" placeholder="自定义按键:huiche" @keyup.huiche="showInfo"><br /><br />
<!-- 同时按下Ctrl和y才可触发事件 -->
<input type="text" placeholder="按下ctrl触发事件" @keydown.ctrl="showInfo"></input><br /><br />
<input type="text" placeholder="同时按下ctrl和y触发事件" @keydown.ctrl.y="showInfo"></input><br />
</div>
<script>
Vue.config.keyCodes.huiche = 13//定义了一个别名按键
const vm = new Vue({
el: '#root',
data: {
name: '尚硅谷'
},
methods: {
showInfo(e) {
// if(e.keyCode===13)
// return console.log(e.target.value);
// console.log(e.key);//获取键的名字
// console.log(e.keyCode);//获取键的值
console.log(e.target.value);
}
}
})
</script>
</body>
</html>
总结:
1,Vue中常用的按键别名:
回车=》enter(一般使用keyup)
删除=》delete(捕获“删除”和“退格”键)
退出=》esc
空格=》space
换行=》tab(特殊,必须和keydown一起使用)
上=》up
下=》down
左=》left
右=》right
2,Vue未提供别名的按键,可以使用按键原始的key值去绑定,但要注意转为kebab-case(短横线命名)
3,系统修饰键(用法特殊):ctrl,alt,shift,meta
(1),配合keyup使用:按下修饰键的同事,再按下其他键,随后释放其他键,时间才被触发(例如ctrl.y)
(2),配合keydown使用:正常触发事件
4,也可以使用keyCode去指定具体的按键(不推荐 @keyup.13)
5,Vue.config.keyCodes.自定义键名 = 键码.可以去定制按键别名(Vue.config.keyCodes.huiche = 13)