VUE中Vue.nextTick()和this.$nextTick()怎麼使用?
官方文檔是這樣解釋的:dom
在下次 DOM 更新循環結束以後執行延遲迴調。在修改數據以後當即使用這個方法,獲取更新後的 DOM。函數
雖然 Vue.js 一般鼓勵開發人員沿着「數據驅動」的方式思考,避免直接接觸 DOM,可是有時咱們確實要這麼作。好比你在Vue生命週期的created()鉤子函數進行的DOM操做必定要放在Vue.nextTick()的回調函數中。緣由是什麼呢,緣由是在created()鉤子函數執行的時候DOM 其實並未進行任何渲染,而此時進行DOM操做無異於徒勞,因此此處必定要將DOM操做的js代碼放進Vue.nextTick()的回調函數中。this
Vue.component('example', {
template: '<span>{{ message }}</span>',
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)`,當數據發生變化,更新後執行回調。spa
`Vue.$nextTick(callback)`,當dom發生變化,更新後執行的回調。code
實例:component
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<ul id=
"demo"
>
<li v-
for
=
"item in list"
>{{item}}</div>
</ul>
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渲染已經完成'
)
})
}
}})
|