您的当前位置:首页正文

30 - Vue异步更新 和 $nextTick

来源:华佗健康网

需求: 编辑标题,编辑框自动聚焦

        1. 点击编辑,显示编辑框

        2. 让编辑框,立即获取焦点

this.isShowEdit = true // 显示输入框
this.$refs.inp.focus() // 获取焦点

// 问题: "显示之后" 立即获取焦点是不能成功的!!!
原因: Vue是异步更新 DOM (提升性能) 

$nextTick: 等 DOM 更新后,才会触发执行此方法里的函数体

语法: this.$nextTick(函数体)

this.$nextTick(() => {
    this.$refs.inp.focus()
})

总结:

        1. Vue是异步更新DOM的

        2. 想要在DOM更新完成之后做某件事,可以使用$nextTick

this.$nextTick(() => {
    // 业务逻辑
})

代码示例:

<template>
  <div>
    <!-- 是否在编辑状态 -->
    <div v-if="isShowEdit">
      <input ref="inp" v-model="editValue" type="=text">
      <button>确认</button>
    </div>

    <!-- 默认状态 -->
    <div v-else>
      <span>{{ title }}</span>
      <button @click="handleEdit">编辑</button>
    </div>

  </div>
</template>
<script>
export default {

  data() {
    return {
      title: "大标题",
      editValue: "",
      isShowEdit: false
    }
  },
  methods: {
    handleEdit() {
      // 1.显示输入框 (异步dom更新)
      this.isShowEdit = true
      // 2.让 输入框 获取焦点 ($nextTick等dom更新完,立刻执行准备的函数体)
      this.$nextTick(() => {
        this.$refs.inp.focus()
      })


      // setTimeout没有 $nextTick 精准
      // setTimeout(()=>{
      //   this.$refs.inp.focus()
      // },1000)

    }
  }

}
</script>
<style></style>

因篇幅问题不能全部显示,请点此查看更多更全内容