绑定在特定元素上,创建时绑定
<input @keyup.enter="function">
当没有绑定元素时,将事件绑定到document上
放在created钩子里,页面元素都加载完后执行
//this指向修正
var that = this;
//当前页面监视键盘输入
document.onkeydown = function(e) {
//事件对象
let key = window.event.keyCode;
//键盘按键判断:左箭头-37;上箭头-38;右箭头-39;下箭头-40
if (key == 37) {
//执行methods里的事件
that.left();
} else if (key == 38) {
that.top();
} else if (key == 39) {
that.right();
} else if (key == 40) {
that.bottom();
}
//阻止页面里的默认事件
e.preventDefault();
};
- 注意:
onkerdown这个函数本身又形成了一个"作用域",this指向了调用onkeydown的对象 - 解决方案:
var that = this;用一个全局变量把this保存起来再用