項目中有個點擊顯示搜索並讓搜索框獲取焦點的需求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