在绑定事件中使用 focus 事件需要点两次才会生效的问题

1665395808869

​ 在 vue 的学习过程中,我碰到了这样一个问题。在给上图所示的简单列表元素中添加修改事件时,想要在修改的同时,对文字进行选中聚焦操作,在对元素的修改按钮绑定了这样一个事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
handleEdit(todo){

if(todo.hasOwnProperty.call("isEdit")){

​ todo.isEdit=true;

let k=document.querySelector(".in2");

​ k.focus();

​ }else{

this.$set(todo,"isEdit",true)

let k=document.querySelector(".in2");

​ k.focus();

​ }

​ }

​ 但是此时,在点击了修改 button 以后,只会出现这样的效果

1665396006726

很显然,只是将 input 的 v-show 设为了 true,显示出了框而并未实现聚焦效果,需要点击两次才有效果。

添加了一系列事件后,我发现是因为在绑定事件的时候,事件的绑定与实例加载在将元素放到页面之前,而 focus 这个事件需要对已经在页面的元素进行操作,所以第一次点击时无法实现。所以我给设定的事件加了个定时器,如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
handleEdit**(todo){

if(todo.hasOwnProperty.call("isEdit")){

​ todo.isEdit=true;
let k=document.querySelector(".in2");

setTimeout(()=>{

​ k.focus();

​ },3000)

​ }else{

this.$set(todo,"isEdit",true)

let k=document.querySelector(".in2");

setTimeout(()=>{

​ k.focus();

​ },1)

​ }

​ }

问题解决。