首页 前端笔记 正文
  • 本文约463字,阅读需2分钟
  • 76
  • 0

Vue异步更新和$nextTick

1.首先给一个按钮 绑定点击事件

2.在 handleEdit 里做两个事情 显示输入框 并让输入框显示焦点

3.Vue属于异步更新的DOM 想要在DOM更新完成后 在执行下一步 有两个办法

3.1使用 定时器 只不过不是很精准 需要在固定的时间内在执行

setTimeout(()=>{
      this.$refs.inp.focus()
    },1000)

3.2使用 $nextTick  会在DOM更新完成之后再去执行下面的业务逻辑

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

完整代码:

<template>
  <div class="app">
    <div v-if="isShowEdit">
      <input type="text" v-model="editValue" ref="inp" />
      <button>确认</button>
    </div>
    <div v-else>
      <span>{{ title }}</span>
      <!-- 给编辑注册点击事件 -->
      <button @click="handleEdit">编辑</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      title: '大标题',
      // 给isShowEdit 赋初值
      isShowEdit: false,
      editValue: '',
    }
  },
  methods: {
   handleEdit(){
    // 隐藏标题 并显示输入框
    this.isShowEdit = true

    // 让输入框获取焦点
    this.$nextTick(()=>{
      this.$refs.inp.focus()
    })
   }
  },
}
</script>
标签:前端笔记
温馨提示:本文最后更新于2024年3月14日 17:41,若内容或图片失效,请在下方留言或联系博主。
评论