Enter the vue project to delete data (step on the pit record)

When changing the bug today, the product said that you need to click the Enter key to delete the data

So I first injected the event of listening to the keyboard key in the component

created() {
   //监听键盘按下事件
    window.addEventListener('keydown', this.handEnterCode, true)
},

Then, I added a method to trigger keyboard events in methods

methods:{
    // 回车键盘触发该方法
    handEnterCode(e) {
       if(e.keyCode === 13){
           // 删除数据的方法
           this.submitPopupData()
       }
    },
}

 Finally, you need to remove the change event when you leave this page, otherwise you will trigger the change method by pressing Enter on another page, resulting in a bad experience

destroyed(){
 //销毁回车事件,如果不销毁,在其他页面敲回车也会执行回车登录操作。
   window.removeEventListener('keydown',this.keyDown,false);
 }

I thought that everything would be fine in this way, and this function was perfectly realized, but another bug appeared while playing, watch the video below

enter enter bug video

At first, I guessed that the reason for this problem was that the keyboard event was not removed after the trigger was completed, so I removed the event in the successful deletion, but it still had no effect, so I played a few more times and found a problem , as long as the press enter delete is successful, continue to press enter, it will always trigger the delete box event, and then press enter will continue to delete the data, but if I delete the data after the first press enter, after closing, click any button on the page After that or after clicking any blank space, there will be no such problem after continuing to press Enter, so I guess it is the problem of event bubbling (click the delete button for the first time to pop up the delete box, if you do not perform any operations at this time, the last time The old event is still left over due to bubbling, so after the first press enter to delete, because of the existence of legacy events, the second press enter will still evoke the delete pop-up window, and click again to delete directly, resulting in a new one bug), click elsewhere to clear this legacy event, so find the problem and solve it, we can clear the bubbling event after triggering the Enter key

methods:{
    // 回车键盘触发该方法
    handEnterCode(e) {
      // 这句话可以阻止回车事件冒泡;如果注释掉这句话,那么会事件残余
       e.preventDefault()
       if(e.keyCode === 13){
           // 删除数据的方法
           this.submitPopupData()
       }
    },
}

Guess you like

Origin blog.csdn.net/weixin_40565812/article/details/130373998