为了在数据变化之后等待 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