Vue 3:模拟按钮点击并传递与实际点击时相同的$事件



我有以下按钮,当点击它时,我会向其添加顺风animate-pulse,然后在动画播放完成后将其删除:

<button              
class="
bg-transparent
text-black
font-bold
py-2
px-4
rounded-sm
uppercase                
"
v-bind:class="{
'hover:bg-magnolia-700': hasResponded,
'opacity-30': !hasResponded,
}"                   
v-on:click="($event) => $event.target.classList.add('animate-pulse')"
v-on:animationend="($event) => $event.target.classList.remove('animate-pulse')"
ref="nextButton"
>
Next
</button>

我还有一个eventListener,它可以检查键盘上是否按下了右箭头或左箭头:

created() {
var self = this;
window.addEventListener("keydown", function (e) {
switch (e.key) {
case "ArrowLeft":
self.clickPrevious();
break;
case "ArrowRight":
this.$refs.nextButton.click();
}
});
},

正如你所看到的,我想模拟按钮点击this.$refs.nextButton.click();。然而,这会导致错误:

SingleItemSection.vue:281 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'classList')

由于使用keydown Listener时未传递实际按钮($event.target(。我如何模拟这一点,就好像用户要点击实际按钮(即传递相同的$事件(一样?

我只需要添加这两个不带参数的方法,并以相同的方式从模板和事件侦听器调用它们:

created() {
const self = this;
window.addEventListener("keydown", function (e) {
switch (e.key) {
case "ArrowLeft":
self.addAnimateToPrev();
break;
case "ArrowRight":
self.addAnimateToNext();
}
});
},
methods: {
addAnimateToNext() {
this.$refs.nextButton.classList.add('animate-pulse')
},
addAnimateToPrev() {
this.$refs.prevButton.classList.add('animate-pulse')
}
}

并且在模板中:v-on:click="addAnimateToNext"

最新更新