[英]How do I keep the focus on an input, after i click on a button without flickering in Vue 3?
Script脚本
const amountRef = ref(null);
const amount = ref(0.1);
const insertSuggestion = (e, value) => {
e.preventDefault();
e.stopPropagation();
amount.value = value;
amountRef.value.focus();
};
Template模板
<Suggestion
class="..."
v-for="suggestion in suggestions"
:key="suggestion"
@click="insertSuggestion($event, suggestion)"
>
{{ suggestion }}
</Suggestion>
<input
class="..."
@keyup.enter="handleBuy"
placeholder="Amount"
ref="amountRef"
v-model="amount"
/>
You could try to capture the blur event and add the classes back if the relatedTarget
is one of those buttons.如果
relatedTarget
是这些按钮之一,您可以尝试捕获模糊事件并重新添加类。 Super psuedo code below:超级伪代码如下:
<input
class="..."
@keyup.enter="handleBuy"
@blur="maybeMimicFocus"
placeholder="Amount"
ref="amountRef"
v-model="amount"
/>
maybeMimicFocus (event) {
if (event.relatedTarget && event.relatedTarget.tagname === 'btn') {
this.$refs.amountRef.$el.classList.add('the-classes-that-make-it-look-focused')
}
}
the browser won't have to repaint the dom and therefore this transaction should be so quick that the naked eye won't see it a difference.浏览器不必重新绘制 dom,因此该事务应该非常快,以至于肉眼不会看到它有什么不同。 the only caveat I can see is if there are animations attached to transitioning properties in which those will have to fire.
我能看到的唯一警告是,是否有动画附加到必须触发的过渡属性。
You can re-focus the input element on the blur
event:您可以将输入元素重新聚焦在
blur
事件上:
<input ref="amountRef" @blur="$refs.amountRef.focus()"/>
Edit编辑
You also need to check the relatedTarget
of the blur
event to make sure you only re-focus when one of the buttons is clicked.您还需要检查
blur
事件的relatedTarget
以确保仅在单击其中一个按钮时重新聚焦。
Note: this solution does not work on Firefox.注意:此解决方案不适用于 Firefox。
<Suggestion
class="suggestion-btn"
...
>
</Suggestion>
<input
ref="amountRef"
@blur="onBlur"
/>
onBlur(evt) {
if (
evt.relatedTarget &&
evt.relatedTarget.classList.contains("suggestion-btn")
) {
this.$refs.amountRef.focus();
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.