Vue--实现一个简单的搜索框-$nextTick方法

目录

$nextTick:

案例思路:


$nextTick:

当某一些代码需要延迟执行的时候,我们可以使用Vue提供的$nextTick方法

语法:this.$nextTick(callback)

组件的$nextTick方法会把回调推迟到下一个DOM更新周期结束之后再执行

等组件DOM更新完成之后再执行回调函数,可以保证 callback可以操作到最新的DOM元素

案例思路:

点击搜索按钮-->搜索按钮消失、文本框显示并自动获取焦点

点击其他区域-->文本框失去焦点-->文本框消失,搜索按钮显示

<template>
  <div id="app">
    <p>我是App.vue文件</p>

    <div class="serach">
      <input type="text" v-if="inputSet" @blur="inputRemove" ref="inputRef">
      <button v-else @click="getInput">搜索</button>
    </div>

  </div>
</template>

<script>
export default {
  data(){
    return{
      inputSet:false
    }
  },
  methods:{
    getInput(){
      this.inputSet = true
      this.$nextTick(()=> {
        this.$refs.inputRef.focus()
      })
    },
    inputRemove(){
      this.inputSet = false
    }
  }
}
</script>

<style lang="less" scoped>
*{
  margin: 0;
  padding: 0;
}
#app{
  position: relative;
  width: 100%;
  height: 10rem;
  background-color: antiquewhite;
  p{
    text-align: center;
    font-weight: bold;
    font-size: 20px;
    color: #286e6e;
  }
  .serach{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    display: flex;
    width: 300px;
    height: 30px;
    border: 1px solid #000;
    border-radius: 6px;
    overflow: hidden;
    input{
      flex: 8;
      border: 0;
      outline: none;
      padding: 5px;
    }
    button{
      flex: 2;
      border: 0;
      border-left: 1px solid #666;
      font-weight: bold;
      background-color:#68dcdc;
    }
  }
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_63836026/article/details/124531100