vue nextTick用法

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

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

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

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

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

<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>

亲测可用,特此记录!

    原文作者:trust2018
    原文地址: https://segmentfault.com/a/1190000007991925
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞