区别——数据更新-Vue2中this.nextTick和 & dom更新—— vue2中的this.$nextTick 和 vue3中nextTick
this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。
1、官网释义
1.1、nextTick-数据更新
vue3.0中,链接-https://v3.cn.vuejs.org/api/global-api.html#nexttick
将回调推迟到下一个 DOM 更新周期之后执行。在更改了一些数据以等待 DOM 更新后立即使用它。
import { createApp, nextTick } from 'vue'
const app = createApp({
setup() {
const message = ref('Hello!')
const changeMessage = async newMessage => {
message.value = newMessage
await nextTick()
console.log('Now DOM is updated')
}
}
})
1.2、$nextTick-dom更新
vue2.0中,链接-https://v3.cn.vuejs.org/api/instance-methods.html#nexttick
-
参数:
{Function} [callback]
-
用法:
将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法
nextTick
一样,不同的是回调的this
自动绑定到调用它的实例上。 -
示例:
createApp({
// ...
methods: {
// ...
example() {
// 修改数据
this.message = 'changed'
// DOM 尚未更新
this.$nextTick(function() {
// DOM 现在更新了
// `this` 被绑定到当前实例
this.doSomethingElse()
})
}
}
})
2、示例
2.1、vue2.0中使用$nextTick
index.vue
<template>
<ul id="demo">
<li v-for="item in list">{{item}}</div>
</ul>
</template>
<script>
new Vue({
el:'#demo',
data:{
list=[0,1,2,3,4,5,6,7,8,9,10]
},
methods:{
push:function(){
this.list.push(11);
this.nextTick(function(){
console.log('数据已经更新')
});
this.$nextTick(function(){
console.log('v-for渲染已经完成,dom已经更新')
})
}
}})
</script>
2.2、vue3.0中使用nextTick
index.vue
<template>
<div v-if="otherParam.showA"></div>
</template>
<script lang="ts">
import { reactive, nextTick } from 'vue'
setup () {
const otherParam = reactive({
showA:false
})
// DOM 尚未更新
nextTick(()=>{
// DOM 现在更新了
otherParam.showA = true
})
return {
otherParam
}
}
</script>
vue2中
this.abc = false
this.$nextTick(() => {
//你要执行的方法
this.abc = true
})
总结
Vue.nextTick(callback)
,当数据发生变化,更新后执行回调。Vue.$nextTick(callback)
,当dom发生变化,更新后执行的回调。