場景 : 在我們進行 vue 的項目,遇到這么一個bug,原因:我們在 mounted 發送了異步請求,並且 new swiper()對象,因為 發送請求是異步操作,而new swiper 是同步操作,數據沒有請求回來之前,同步操作就被執行了,所以頁面上的輪播圖,不會進行輪播了,???
解決:子需要讓同步代碼延遲到數據請求回來,DOM完成更新后,就行了
方式一
 但監聽到數據變化時,就可以new swiper了,並且使用 vm.$nextTick()
watch: { 
categorys() {
this.$nextTick(() => {
         new Swiper(".swiper-container", {
           loop: true,  循環模式選項
           autoplay: true,
            如果需要分頁器
           pagination: {
             el: ".swiper-pagination"
           }
         });
       });
     }
   },
 
        方式二
 在進行異步請求事件,傳遞一個回調函數,在那邊判斷函數存不存在,存在,就執行函數,此時,數據被請求之后才會去執行同步代碼,也使用了vm.$nextTick()
 this.$store.dispatch(ASYNCH_CATEGORYS, () => {  方式二
       this.$nextTick(() => {
         new Swiper(".swiper-container", {
           loop: true,  循環模式選項
           autoplay: true,
            如果需要分頁器
           pagination: {
             el: ".swiper-pagination"
           }
         });
       });
     });  
 
        方式三
 async + await
 async mounted() { // 方式三
    await this.$store.dispatch(ASYNCH_POSITION); // 獲取位置信息
    await this.$store.dispatch(ASYNCH_CATEGORYS);
    this.$nextTick(() => {
      new Swiper(".swiper-container", {
        loop: true, // 循環模式選項
        autoplay: true,
        // 如果需要分頁器
        pagination: {
          el: ".swiper-pagination"
        }
      });
    });
 
       