先說一下產品需求,就是有幾個tab欄,每個tab欄對應的ajax請求不一樣,內容區域一樣,內容為實時刷新數據,每3s需要重新請求,返回的數據在內容區域展示,每點擊一次tab欄需停止其他tab欄ajax請求,防止阻塞,首次加載頁面的時候又不能5個ajax同時請求,只需要請求第一個就好
也沒有必要建立5個區域,控制顯示隱藏,浪費性能,業務代碼就不貼了,把大概原理的代碼貼上來

先是用jq實現了一版
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="renderer" content="webkit"> <title>Title</title> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script></head><body><div> <ul> <li>click</li> <li>click</li> <li>click</li> <li>click</li> <li>click</li> </ul></div><script> var arr=[ function(){console.log(0);}, function(){console.log(1);}, function(){console.log(2);}, function(){console.log(3);}, function(){console.log(4);} ]; var seti=setInterval(arr[0],1000) $('li').click(function(){ clearInterval(seti) seti=setInterval(arr[$(this).index()],1000) })</script></body></html>再看vue版
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="renderer" content="webkit"> <title>Title</title> <script src="https://unpkg.com/vue@2.2.6/dist/vue.min.js"></script></head><body><div id="vm"> <button @click="tab(0)">click0</button> <button @click="tab(1)">click1</button> <button @click="tab(2)">click2</button> <button @click="tab(3)">click3</button> <button @click="tab(4)">click4</button> <div> <p>{{show}}</p> </div></div><script> var vm1 = new Vue({ el: '#vm', data: { arr:[ function(){console.log(0);}, function(){console.log(1);}, function(){console.log(2);}, function(){console.log(3);}, function(){console.log(4);} ], time1:'', time2:'', show:'', num:0, }, methods: { tab: function(index){ //如果每個tab的方法不一樣,提前用一個數組把方法保存起來 clearInterval(this.time1) this.time1=setInterval(this.arr[index],1000) //以下是調用同一種方法的時候可以不需要設置數組 this.num = 0 clearInterval(this.time2) this.time2 = this.fun(index) }, fun:function(index){ var _this=this; return setInterval(function(){ //寫個隨機數顯示在頁面,具體業務需求應該是ajax請求 var random=String(parseInt(Math.random()*100000000000)) //字符一個一個顯示在頁面上 _this.show=index+random.substring(0,_this.num++); },300) } }, mounted:function(){ this.time1=setInterval(this.arr[0],1000) } });</script></body></html>以上所述是小編給大家介紹的基于Vue實現tab欄切換內容不斷實時刷新數據功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答