vue-router4 配置懒加载 页面加载时展示loading

发布时间 2023-04-26 16:21:59作者: 飞尽堂前燕

 

懒加载写法

{
    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')
  },

]