项目中有个点击显示搜索并让搜索框获取焦点的需求

1
2
3
4
showsou(){//点击显示搜索框并获取焦点的函数
this.showit = true
document.getElementById("keywords").focus()
}

按照这种写法,搜索框可以显示,但并未获取焦点,最后看官方文档受到了启发

1
2
3
4
5
6
// 修改数据
vm.msg = 'Hello'
// DOM 还没有更新
Vue.nextTick(function () {
// DOM 更新了
})

使用vue nextTick可以解决,最终代码如下

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<template>
<div id="app">
<img src="./assets/logo.png">
<div class="soubox">
<button class="showsearch" @click="showsou">搜索</button>
<div class="sou" v-show="showit">
<input type="text" name="" id="keywords">
<div class="closesou" @click="hidesou">X</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
showit: false
}
},
methods:{
showsou(){
this.showit = true
this.$nextTick(function () {
// DOM 更新了
document.getElementById("keywords").focus()
})
},
hidesou(){
this.showit = false
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.soubox{position: relative;width:300px;margin:0 auto;}
.sou{position: absolute;left: 0;top:100%;width:100%;}
.closesou{font-size:30px;color:red;cursor: pointer;}
</style>

亲测可用,特此记录!