分享一下 Vue 中 nextTick 的使用

wj2015發表於2021-01-17

目的

理解下 nextTick 的作用和幾個簡單的使用場景

正文

起什麼作用?

在下次 DOM 更新迴圈結束之後執行延遲迴調。在修改資料之後立即使用這個方法,獲取更新後的 DOM。

我想各位都知道或瞭解 Vue 的渲染流程,Vue 在監聽到資料變化後會重新渲染,配合 VDOM 更新真實的 DOM,而 nextTick 的觸發時機就是在呼叫方法後的第一次重新渲染完畢後。

分享一下 Vue 中 nextTick 的使用

如何使用?

有兩種使用方法,一種是傳入回撥,另一種是 Promise,官方使用示例如下:

// 修改資料
vm.msg = 'Hello'
// DOM 還沒有更新
Vue.nextTick(function () {
  // DOM 更新了
})

// 作為一個 Promise 使用 (2.1.0 起新增,詳見接下來的提示)
Vue.nextTick()
  .then(function () {
    // DOM 更新了
  })

如果在 SPA(單檔案元件) 中,可能是這個樣子

<template>
  <div id="test">{{msg}}</div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      "msg": "Hello World!"
    }
  },
  method() {
    this.msg = "Hi World!";
    this.$nextTick(() => {
      console.log('DOM updated:', document.getElementById('test').innerHTML)
    });
  }
}
</script>

有什麼使用場景?

需要等待渲染完成後執行的一些方法

初始化繫結或操作 DOM

比如在 createdmounted 回撥中,需要操作渲染好的 DOM,則需要在 nextTick 中執行相關邏輯,這在必須使用一些老的需要繫結 DOM 的庫時很有用。

比如,在載入 UEditor 時,可能會這樣玩

<template>
<script  id="container"  name="content"  type="text/plain">  這裡寫你的初始化內容  </script>
</template>
<script>
export default {
    mounted() {
        this.nextTick(() => {
            var ue = UE.getEditor('container');
        });
    }
}

獲取元素寬度

在 Vue 中獲取元素寬度有兩種方式,第一種是通過 $refs[ref名稱].style.width,第二種可以使用傳統操作 DOM 的方式獲取,但這兩者要獲取到準確的元素寬度,則需要在 DOM 渲染完畢後執行。

<template>
<p ref="myWidth" v-if="showMe">{{ message }}</p>  <button @click="getMyWidth">獲取p元素寬度</button>
</template>
<script>
export default {
  data() {
    return {
      message: "Hello world!",
      showMe: false,
    },
    methods: {
      getMyWidth() {
        this.showMe = true;
        //this.message = this.$refs.myWidth.offsetWidth; 
        //報錯 TypeError: this.$refs.myWidth is undefined 
        this.$nextTick(()=>{
        //dom元素更新後執行,此時能拿到p元素的屬性  
        this.message = this.$refs.myWidth.offsetWidth; })
      }
    }
  }
}
</script>

總結

雖說 Vue 的設計理念並不建議我們去直接操作 DOM,但有些場景下出現了特別令人迷惑的問題,理解 Vue 的渲染邏輯後,使用 nextTick() 可以解決。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章