The role and use of $nextTick in Vue

It is mainly used to deal with the problem that the DOM has not been updated in time after the data changes dynamically. NextTick can be used to obtain the latest DOM changes after the data update.

Scenario 1: Click the button to get the width of 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>

Scenario 2: Click the button to get the focus of the input box

<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>

In addition, there are many application scenarios for nextTick, including the functions of adding and editing forms, and the bug of displaying data in the same modal box can also be solved by using it.

Guess you like

Origin blog.csdn.net/qq_72760247/article/details/128770741