When we design an input box, we usually have an icon behind it that deletes the input and doesn’t lose focus when the input box gets focus. When the input box loses focus, the icon behind it disappears.
So deleting an icon is bound to a click event that clears the input field when we click on the delete icon.
When we click the delete button, the input blur event is triggered. The blur event loses focus and hides the delete icon. The blur event is executed before the icon’s click event, and the icon disappears, let alone the click event.
Problems demonstrate
The solution
We can also add a mouseDown event for button removal, in which event.preventDefault() prevents browser default events so that the input field doesn’t lose focus when the button is clicked.
Of course you could simply change the click event to a mousedown event, since mousedown events are executed before blur events and prevent the default behavior, but the above option is recommended.
After the solution
The sample code
<template> <div> <div class="frame"> <input type="text" class="input" ref="input" @focus="onFocus" @blur="onBlur" /> <div v-show="isFocus" class="del" @click="clearInput" @mousedown.prevent> X </div> </div> </div> </template> <script lang="ts"> import { ref } from "vue"; export default { name: "App", setup() { let input = ref(); const clearInput = (): void => { input.value.value = ""; }; let isFocus = ref<boolean>(false); const onBlur = (): void => { isFocus.value = false; }; const onFocus = (): void => { isFocus.value = true; }; return { input, clearInput, onBlur, onFocus, isFocus, }; }}; </script> <style scoped> .frame { display: flex; align-items: center; justify-content: center; gap: 5px; width: 200px; height: 32px; border: 1px solid #dcdfe6; } .input { outline: none; border: 0px; flex: 8; } .del { color: #dcdfe6; flex: 2; } </style>Copy the code