vue nextTick用法

本文介绍如何在Vue项目中实现点击按钮后显示搜索框,并使搜索框自动获得焦点的功能。通过使用Vue的nextTick方法确保DOM更新后再进行焦点操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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>

亲测可用,特此记录!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值