vue更新DOM之后的回調方法


為了在數據變化之后等待 Vue 完成更新 DOM,可以在數據變化之后立即使用Vue.nextTick(callback)。這樣回調函數將在 DOM 更新完成后被調用。

在組件內使用 vm.$nextTick() 實例方法特別方便,因為它不需要全局 Vue,並且回調函數中的 this 將自動綁定到當前的 Vue 實例上。

為了在數據更新操作之后操作DOM,我們可以在數據變化之后立即使用Vue.nextTick(callback);這樣回調函數會在DOM更新完成后被調用,就可以拿到最新的DOM元素了。

//第一個demo
this.msg = '我是測試文字'
this.$nextTick(()=>{
    //20
    console.log(document.querySelector('.msg').offsetHeight)
})
//第二個demo
this.childName = '我是子組件名字'
this.$nextTick(()=>{
    //子組件name:我是子組件名字
    this.$refs.child.showName()
})
 
        


例如,清空輸入框之后光標定位到輸入框

<div class="dataSearch fr">
  <input type="text" class="dataSearch_input fl" ref="searchinput" v-model="searchval" placeholder="搜索">
  <input type="button" class="dataSearch_bnt fl" @click="search">
  <i class="cancelSearch" v-show="searchval" @click="searchval='';$nextTick(() => $refs.searchinput.focus());"></i> 
</div>

 

methods下寫:

methods: {
    ondbclick() {
        this.isEdit = true;
        this.$nextTick(() => this.$refs.editTask.focus());
    },
}

 來源

https://zhuanlan.zhihu.com/p/138186879


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM