正确使用Vue里的nextTick方法


使用Swiper做一个移动端轮播插件,需要先异步动态加载数据后,然后使用v-for渲染节点,再执行插件的滑动轮播行为。解决这个问题,我们通过在组件中使用vm.$nextTick来解决这一需求。

一、vm.$nextTick( [callback] )

image.png

 

二、Vue.nextTick( [callback, context] )

image.png

三、异步更新队列

image.png

 

实例:

 

 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发生变化,更新后执行的回调。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM