nextTick 方法
原理:
nextTick(),是将回调函数延迟在下一次DOM更新数据过后进行调用。
简单的理解就是:当数据更新之后,DOM进行渲染之后将会自动进行执行该函数。
<template>
<div class="hello">
<div>
<button id="firstBtn" @click="testClick()" ref="hello">{{testMsg}}</button>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
testMag : '初始值',
}
},
methods :{
testClick: function(){
let that=this;
that.testMsg='修改之后的值';
console.log(that.$refs.hello.innerText);
}
}
}
</script>
使用this.$nextTick()之后
methods :{
testClick: function(){
let that=this;
that.testMsg='修改之后的值';
that.$nextTick(function(){
console.log(that.$refs.hello.innerText);
});
}
}
注意:并不是数据进行变化之后DOM立即进行变化,而是按照一定的策略进行DOM的更新。$nextTick是在下次DOM更新循环结束之后执行延迟回调,在修改数据之后使用 $nextTick,则可以在回调中获取更新后的DOM。
什么时候需要用到Vue.nextTick()?
Vue生命周期的created()钩子函数进行的DOM操作一定要放在Vue.nextTick()的回调函数中,原因是在created()钩子函数执行的时候DOM其实并未进行渲染,而此时进行DOM操作是徒劳的,所以一定要将DOM操作的js代码放到Vue.nextTick()的回调函数中。与之对应的就是mounted钩子函数,因为该钩子函数执行时所有的DOM挂载已完成。
created(){
const that=this;
that.$nextTick(function(){
that.$refs.hello.innerHTML='created中更改了按钮内容';
})
},