vue 的this.$nextTick(()=>{})作用

1.html
<div id="example">
  <my-component></my-component>
</div>
2.js
Vue.component('my-component', {
  template: '<div @click="click"><p id="p" ref="inp">123</p>{{message}}<p ref="inp" @click="pClick">{{age}}</p></div>',
  data(){
  	return {
    	message:'A custom component!',
      age:09090909
    }
  },
  mounted(){
  	this.$nextTick(()=>{
    	console.log(this.$el.textContent)
    })
  },
  methods:{
  	click:function(){
    	this.message = "hello world";
    	console.log(this.$el.textContent,'1')
      this.$nextTick(()=>{
      	console.log(this.$el.textContent,'2')
      })
    },
    pClick:function(){
    	this.age = 8888
    }
  }
})

// 创建根实例
new Vue({
  el: '#example',
})

理解:当data中的某个属性改变的时候,这个值并不是立即渲染到页面上,而是先放到watcher队列上(异步),只有当前任务空闲的时候才会去执行watcher队列上的任务。所以导致,改变的数据挂载到dom上会有一定的延迟,这也就导致了,当我们在改变属性值的时候,立即通过dom去拿改变的值时发现拿到的值并不是改变的值,而是之前的值。


this.$nextTick作用:在下次dom更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获得更新后的dom


猜你喜欢

转载自blog.csdn.net/lhb215215/article/details/79173232