项目中有个点击显示搜索并让搜索框获取焦点的需求vue
showsou(){//点击显示搜索框并获取焦点的函数 this.showit = true document.getElementById("keywords").focus() }
按照这种写法,搜索框能够显示,但并未获取焦点,最后看官方文档受到了启发web
// 修改数据 vm.msg = 'Hello' // DOM 尚未更新 Vue.nextTick(function () { // DOM 更新了 })
使用vue nextTick能够解决,最终代码以下app
<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>
亲测可用,特此记录!ide