應用場景
需要在視圖更新之后,基於新的視圖進行操作
文檔說明
在下次 DOM 更新循環結束之后執行延遲回調。在修改數據之后立即使用這個方法,獲取更新后的 DOM
nextTick原理
1、異步說明
Vue 實現響應式並不是數據發生變化之后 DOM 立即變化,而是按一定的策略進行 DOM 的更新
2、事件循環說明
簡單來說,Vue 在修改數據后,視圖不會立刻更新,而是等同一事件循環中的所有數據變化完成之后,再統一進行視圖更新。
created、mounted
在 created 和 mounted 階段,如果需要操作渲染后的試圖,也要使用 nextTick 方法。
注意 mounted 不會承諾所有的子組件也都一起被掛載。如果你希望等到整個視圖都渲染完畢,可以用 vm.$nextTick 替換掉 mounted
mounted: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
}
以下使用nexttick的三種情況
1、點擊按鈕顯示原本以 v-show = false 隱藏起來的輸入框,並獲取焦點。
showsou(){
this.showit = true //修改 v-show
document.getElementById("keywords").focus() //在第一個 tick 里,獲取不到輸入框,自然也獲取不到焦點
}
修改為:
showsou(){
this.showit = true
this.$nextTick(function () {
// DOM 更新了
document.getElementById("keywords").focus()
})
}
2、點擊獲取元素寬度。
<div id="app">
<p ref="myWidth" v-if="showMe">{{ message }}</p>
<button @click="getMyWidth">獲取p元素寬度</button>
</div>
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;
})
}
3、使用 swiper 插件通過 ajax 請求圖片后的滑動問題。
參考閱讀:
https://segmentfault.com/a/1190000012861862?utm_source=tag-newest