最近项目开发中遇到的小问题,只能说前端的技术一直在更新,需要不断学习才能在这个大时代,超级卷的时代不被淘汰,好了直接上内容。
之前在做键盘事件的时候 回车事件是依据e.keyCode 我们可以先绑定一下键盘的事件
<template>
<div tabindex="1" @keydown="keydown" style="display: flex;">
<div
v-for="item, index in list"
:key="index"
:class="currentIndex === index ? 'active' : ''"
>{{ item.name }}</div>
</div>
</template>
然后打印这个这个e
const keydown = (e: KeyboardEvent) => {
console.log(e);
}
那么我们就可以看见这个打印出来,挂载在他的原型上都有那些属性,以前我们再去做这类问题时,直接是找他他下面的keyCode属性,然后直接进行判断去赋予执行的事件。
但是这次因为要做的项目是获取锚点 需要监听键盘事件,然后在按照以前的写法,就出现这种情况
以前百试不灵的写法,这次竟然出现这种情况,查阅资料发现,原来这种写法快要被官方淘汰了,官方的建议是,尽量在项目中摒弃这种写法,因为可能哪天就要失效了,那么来正解吧:
const keydown = (e: KeyboardEvent) => {
console.log(e);
if (e.key === "ArrowRight") {
if (currentIndex.value < 0) {
return
} else if (currentIndex.value >= (list.value.length-1)) {
return
}else {
currentIndex.value++
}
} else if (e.key === "ArrowLeft") {
if (currentIndex.value <= 0) {
return
} else if (currentIndex.value >= list.value.length) {
return
}else {
currentIndex.value--
}
}
console.log(e)
console.log(list.value[currentIndex.value].name)
}
依旧e.key 下面挂载的原型属性,去对应的找你需要监听的键盘事件,好了,这个问题就过了,其实也是在时时刻刻给自己提醒,前端的技术进步真的太快了,尤大大也说了,vue3.0已成默认版本,还是提起战刀继续学习吧。