vue使用this.$nextTick()函数
2020-06-28 本文已影响0人
小李不小
Vue.nextTick
可能看很多理念,不会特别懂,不用担心,先就记住这句话就行 " 数据被更新了,Vue.nextTick 就会触发"。
Vue 中的 nextTick 涉及到 Vue 中 DOM 的异步更新
Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。
nextTick,则可以在回调中获取更新后的 DOM,API 文档中官方示例如下:
new Vue({
// ...
methods: {
// ...
example: function () {
// modify data
this.message = 'changed'
// DOM is not updated yet
this.$nextTick(function () {
// DOM is now updated
// `this` is bound to the current instance
this.doSomethingElse()
})
}
}
Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。
通过案例理解
<div class="app">
<div ref="msgDiv">{{msg}}</div>
<div v-if="msg1">Message got outside $nextTick: {{msg1}}</div>
<div v-if="msg2">Message got inside $nextTick: {{msg2}}</div>
<div v-if="msg3">Message got outside $nextTick: {{msg3}}</div>
<button @click="changeMsg">
Change the Message
</button>
<div>
<div>{{up}}</div>
<el-button type="primary" round @click="nextTick">this.nextTick 当前数据更新后执行函数</el-button>
</div>
</div>
new Vue({
el: '.app',
data: {
msg: 'Hello Vue.',
msg1: '',
msg2: '',
msg3: '',
up:'我是未更新的数据',
},
methods: {
nextTick(){
this.up='我被更新了'
this.$nextTick(()=>{
console.log('我是nextTick,我被执行了')
})
},
changeMsg() {
this.msg = "Hello world."
this.msg1 = this.$refs.msgDiv.innerHTML
this.$nextTick(() => {
this.msg2 = this.$refs.msgDiv.innerHTML
})
this.msg3 = this.$refs.msgDiv.innerHTML
}
}
})
未指定 nextTick 中的 this.$nextTick方法的时候,界面是显示初始化内容,看下图:

当我执行了 nextTick 方法时候,up值被改变之后,this.$nextTick的方法也被执行了。看下图
