Vue $nextTick 解决 v-if 切换后操作 DOM 报错问题

Vue About 794 words

场景

控制v-ifinputVisible变量来显示input输入框,但输入框显示后需要获取焦点。

<template>
  <div>
    <div>
      <input v-if="inputVisible" ref="inputRef" type="text" placeholder="请输入">
    </div>

    <button @click="showInput">展示按钮</button>
  </div>
</template>

$nextTick

如果直接在改变v-if可见性后对DOM进行操作会报错,因为此时DOM还没开始渲染,还没开始走updated生命周期。

使用this.$nextTick(callback function)接收DOM渲染完毕的回调,在回调函数中对元素进行操作。

export default {
  name: "NextTick",
  data: () => ({
    inputVisible: false
  }),
  methods: {
    showInput() {
      this.inputVisible = true
      // DOM渲染完毕才能执行,因为此时生命周期还没走到渲染 input 组件
      // this.$refs.inputRef.focus()
      // this.$nextTick 等到 DOM 渲染完毕才执行 callback 中的回调
      this.$nextTick(()=>{
        this.$refs.inputRef.focus()
      })
    }
  }
}
Views: 1,067 · Posted: 2022-12-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh