关于Vue的api中的this.$nextTick()

it2023-07-28  71

参数:

{Function} [callback]

用法:

将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。

//第一个例子 <template> <div> <div ref="hello"> <h1>{{value}}</h1> </div> <button @click="get">点击</button> </div> </template> <script> export default { data(){ return{ value:'hello,world!' } }, methods:{ get(){ // this.value = '你好' // console.log(this.$refs['hello'].innerHTML); // this.$nextTick(()=>{ // console.log(this.$refs['hello'].innerHTML) // }) } }, mounted(){ console.log('mounted'); console.log(this.$refs['hello']) this.$nextTick(()=>{ console.log('Dom改变了mounted') console.log(this.$refs['hello']) }) }, created(){ console.log('create'); console.log(this.$refs['hello']) this.$nextTick(()=>{ console.log('Dom改变了created') console.log(this.$refs['hello']) }) } } </script>

从打印的顺序可以看到,在create钩子函数执行DOM时,还未进行渲染,此时对Dom操作无用;而在create钩子函数里面使用this.$nextTick(),可以等待dom生成之后调用。

//第二个例子 <template> <div> <div ref="hello"> <h1>{{value}}</h1> </div> <button @click="get">点击</button> </div> </template> <script> export default { data(){ return{ value:'hello,world!' } }, methods:{ get(){ this.value = '你好' console.log(this.$refs['hello'].innerHTML); this.$nextTick(()=>{ console.log(this.$refs['hello'].innerHTML) }) } } } </script>

点击之后 根据上面的例子可以看出,在方法里直接打印的话, 由于dom元素还没有更新, 因此打印出来的还是未改变之前的值,而通过this.$nextTick()获取到的值为dom更新之后的值

最新回复(0)