申明
请求
- 假定如今有路由/news,/login
- 监听键盘事宜,只允许在/news页面内有效
- 不论背面跳到哪一个页面,都不会触发对应的键盘事宜,只能在/news里才触发
题目
- 没有进入/news之前,按键盘上的键,不会触发事宜,
- 进过/news后,不论有无按键盘上的键,再跳到别的页面,按键盘上的键,都邑触发事宜
代码
srcviewsnews.vue
<template>
<div>
news
</div>
</template>
<script>
export default {
data() {
return {
flag: true, //底部图片列表显现隐蔽
name: "aa"
};
},
methods: {
keyLeft() {
alert(this.name);
},
keyUp() {
alert("向上方向键");
},
keyRight() {
alert("向右方向键");
},
keyDown() {
alert("向下方向键");
},
keys() {
var that = this;
document.onkeydown = function(e) {
let key = window.event.keyCode;
if (key == 37) {
that.keyLeft();
} else if (key == 38) {
that.keyUp();
return false; //有高低转动条的时刻,不向上转动
} else if (key == 39) {
that.keyRight();
} else if (key == 40) {
that.keyDown();
return false; //有高低转动条的时刻,不向上转动
}
};
}
},
created() {
if (this.flag == true && this.$route.path == "/news") {
this.keys();
}
},
mounted() {}
};
</script>