vue-router4 配置懶加載 頁面加載時展示loading

 

懶加載寫法

{
    path: "/",
    name: "index",
    component: () => import("../views/Home.vue"),
  }

  

創建Loading組件 並引入到頂層組件中 使用store控制loading組件是否展示

包裝懶加載寫法

const lazyLoad = (componentPath) => {
  // 注意:componentPath 不能直接賦值 import(componentPath),直接賦值無法找到組件
  return () => new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      store.commit('showLoading');
    }, 500);
    import(`@views/${componentPath}.vue`).then((component) => {
      clearTimeout(timer);
      store.commit('hideLoading');
      resolve(component)
    })
  })
}


export const routes: Array<RouteRecordRaw> = [
    
{
    path: "/",
    name: "index",
    component: lazyLoad('Home')
  },

]

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章