使用Swiper做一個移動端輪播插件,需要先異步動態加載數據后,然后使用v-for渲染節點,再執行插件的滑動輪播行為。解決這個問題,我們通過在組件中使用vm.$nextTick來解決這一需求。
一、vm.$nextTick( [callback] )
二、Vue.nextTick( [callback, context] )
三、異步更新隊列
實例:
1 <ul id="demo"> 2 <li v-for="item in list">{{item}}</div> 3 </ul> 4 5 new Vue({ 6 el:'#demo', 7 data:{ 8 list=[0,1,2,3,4,5,6,7,8,9,10] 9 }, 10 methods:{ 11 push:function(){ 12 this.list.push(11); 13 this.nextTick(function(){ 14 alert('數據已經更新') 15 }); 16 this.$nextTick(function(){ 17 alert('v-for渲染已經完成') 18 }) 19 } 20 }})
或者:
1 this.$http.post(apiUrl) 2 .then((response) => { 3 if (response.data.success) { 4 this.topFocus.data = response.data.data; 5 this.$nextTick(function(){ 6 //渲染完畢 7 }); 8 } 9 }).catch(function(response) { 10 console.log(response); 11 });
總結:
* `Vue.nextTick(callback)`,當數據發生變化,更新后執行回調。
* `Vue.$nextTick(callback)`,當dom發生變化,更新后執行的回調。