Vue中$nextTick的作用及使用

主要用于处理数据动态变化后,DOM还未及时更新的问题,用nextTick就可以获取数据更新后最新DOM的变化。

场景一:点击按钮获取h1的宽度

<template>
  <div>
    <h1 ref="myWidth" v-if="show">{
   
   { message }}</h1>
    <button @click="getWidth">获取h1元素宽度</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      show: false,
      message: ""
    }
  },
  methods: {
    getWidth() {
      this.show = true
      this.$nextTick(() => {
        //这句代码如果不放在nextTick会报错,因为v-if动态创建销毁标签,牵扯到生命周期
        this.message = this.$refs.myWidth.offsetWidth
      })

    }
  }
}
</script>

场景二:点击按钮获取输入框的焦点

<template>
  <div>
    <input type="text" ref="myInput" v-show="show" id="id">
    <button @click="getFocus">获取input元素焦点</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      show: false,
    }
  },
  methods: {
    getFocus() {
      this.show = true
      this.$nextTick(() => {
        document.getElementById("id").focus()
      })

    }
  }
}
</script>

此外,nextTick的应用场景还有很多,包括表单新增和编辑功能,相同模态框显示数据的bug,也可利用其解决。

猜你喜欢

转载自blog.csdn.net/qq_72760247/article/details/128770741