【Vue2】异步更新及nextTick的使用

102 阅读1分钟

原理解析

 <div ref="title">{{ reactiveVal }}</div>
 ...
 data() {
        return {
                reactiveVal:'one'
        }
 }
 ...
 mounted() {
    this.reactiveVal = 123
    console.log('sync',this.reactiveVal,this.$refs.title.innerText); // sync 123 one
    this.$nextTick(()=>{
        console.log('nextTick',this.$refs.title.innerText);// nextTick 123
    })
}
 ...
 

数据同步修改,视图异步更新(this.$refs.title.innerText是获取视图里面的结果,是异步过程) 上面的代码可以在,nexTick中获取更新完成后的dom,也就是

this.$nextTick(()=>{
    console.log('nextTick',this.$refs.title.innerText);// nextTick 123
})