网络编程
位置:首页>> 网络编程>> JavaScript>> vue中的input框点击后不聚焦问题

vue中的input框点击后不聚焦问题

作者:黄金钢铁侠  发布时间:2024-05-02 16:33:12 

标签:input框,点击,不聚焦

input框点击后不聚焦问题

废话不多说直接上代码

哪个地方要写input框  就直接把这一部分代码放上   里面双向绑定的值和事件换上自己定义的  

?<div class="item" @click.stop.prevent="inputPaentClick('input1')">
? ? ? ? <input
? ? ? ? ? ref="input1"
? ? ? ? ? placeholder="请输入搜索关键词"
? ? ? ? ? v-model="value"
? ? ? ? ? @keydown.enter="searchs"
? ? ? ? />
? ? ? </div>

在方法里写上这些

? inputPaentClick(refName) {undefined
? ? ? //解决input框双击才可以聚焦问题
? ? ? this.$nextTick(() => {undefined
? ? ? ? this.$refs[refName] && this.$refs[refName].focus();
? ? ? });
? ? }

只复制这些就行 input里绑定的事件以及要实现的方法 写在这个事件同级的地方   

vue input聚焦的坑

点击按钮,使某个input框聚焦

1、给 input 加个 ref 属性,写个 button 按钮并加个点击事件

<input type="text" ref="input">
<button @click="onFocus"></button>

2、onFocus方法:

onFocus() {
? ? this.$refs.input.focus()
? }

加载页面时自动聚焦

mounted() {
? ? this.$nextTick(() => {
? ? ? this.$refs.input.focus()
? ? })
? },

【坑】

如果input框是隐藏的,点击某个元素让input框显示,同时聚焦,这个时候聚焦效果就不会实现。

解决办法:

点击元素的时候用个变量做标识,然后再watch里面去监听这个变量,通过判断这个变量的值来聚焦,

可以写在setTimeout里面,或者写在nextTick里面即可解决问题;代码如下

watch: {
? ? isClick(){
? ? ? if(this.isClick == false) {
? ? ? ? setTimeout(() => {
? ? ? ? ? this.$refs.input.focus()
? ? ? ? }, 100);
?? ??? ?// this.$nextTick(() => {
? ? ? ? // ? this.$refs.input.focus()
? ? ? ? // });
? ? ? }
? ? }
? }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持asp之家。 

来源:https://blog.csdn.net/hope_lucky/article/details/123690548

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com