vue 之 nextTick 与$nextTick

VUE中Vue.nextTick()和this.$nextTick()怎么使用?
官方文档是这样解释的:

在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

虽然 Vue.js 通常鼓励开发人员沿着“数据驱动”的方式思考,避免直接接触 DOM,但是有时我们确实要这么做。比如你在Vue生命周期的created()钩子函数进行的DOM操作一定要放在Vue.nextTick()的回调函数中。原因是什么呢,原因是在created()钩子函数执行的时候DOM 其实并未进行任何渲染,而此时进行DOM操作无异于徒劳,所以此处一定要将DOM操作的js代码放进Vue.nextTick()的回调函数中。

Vue.component('example', {
template: '{{ message }}',
data: function () {
return {
message: 'not updated'
}
},
methods: {
updateMessage: function () {
this.message = 'updated'
console.log(this.$el.textContent) // => 'not updated'
this.$nextTick(function () {
console.log(this.$el.textContent) // => 'updated'
})
}
}
}
---------------------
`Vue.nextTick(callback)`,当数据发生变化,更新后执行回调。

`Vue.$nextTick(callback)`,当dom发生变化,更新后执行的回调。

实例:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"demo" >
     for = "item in list" >{{item}}
 
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 (){
                 alert( '数据已经更新' )
             });
             this .$nextTick( function (){
                 alert( 'v-for渲染已经完成' )
             })
         }
     }})
 

转载于:https://www.cnblogs.com/sweet-ice/p/10518069.html

你可能感兴趣的:(vue 之 nextTick 与$nextTick)