1. 程式人生 > 其它 >Vue.js中this.$nextTick()的使用與理解

Vue.js中this.$nextTick()的使用與理解

原著地址:https://www.cnblogs.com/jin-zhe/p/9985436.html

this.$nextTick()將回調延遲到下次 DOM 更新迴圈之後執行。在修改資料之後立即使用它,然後等待 DOM 更新。它跟全域性方法 Vue.nextTick 一樣,不同的是回撥的 this 自動繫結到呼叫它的例項上。

假設我們更改了某個dom元素內部的文字,而這時候我們想直接打印出這個被改變後的文字是需要dom更新之後才會實現的,也就好比我們將列印輸出的程式碼放在setTimeout(fn, 0)中;

先來第一個例子看一看

<template>
  <section>
    <div ref="hello">
      <h1>Hello World ~</h1>
    </div>
    <el-button type="danger" @click="get">點選</el-button>
  </section>
</template>
<script>
  export default {
    methods: {
      get() {
      }
    },
    mounted() {
      console.log(333);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(444);
        console.log(this.$refs['hello']);
      });
    },
    created() {
      console.log(111);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(222);
        console.log(this.$refs['hello']);
      });
    }
  }
</script>

可以根據列印的順序看到,在created()鉤子函式執行的時候DOM 其實並未進行任何渲染,而此時進行DOM操作並無作用,而在created()裡使用this.$nextTick()可以等待dom生成以後再來獲取dom物件

然後來看第二個例子

<template>
  <section>
    <h1 ref="hello">{{ value }}</h1>
    <el-button type="danger" @click="get">點選</el-button>
  </section>
</template>
<script>
  export default {
    data() {
      return {
        value: 'Hello World ~'
      };
    },
    methods: {
      get() {
        this.value = '你好啊';
        console.log(this.$refs['hello'].innerText);
        this.$nextTick(() => {
          console.log(this.$refs['hello'].innerText);
        });
      }
    },
    mounted() {
    },
    created() {
    }
  }
</script>

根據上面的例子可以看出,在方法裡直接列印的話, 由於dom元素還沒有更新, 因此打印出來的還是未改變之前的值,而通過this.$nextTick()獲取到的值為dom更新之後的值

this.$nextTick()在頁面互動,尤其是從後臺獲取資料後重新生成dom物件之後的操作有很大的優勢,這裡只是簡單的例子,實際應用中更為好用~

嗯,就醬~~