vue-router懒加载添加loading效果

项目中使用了路由懒加载,但是当用户网路不佳的情况下,点击一个新的模块后就不会有任何反应,给人一种点击无效的错觉,所以加个loading还是有必要的。

制作loading

我是自己写的loading;如果用UI的loading也是可以的

/* routerLoading.css */

#routerLoading {
  z-index: 1000;
  position: fixed;
  top: 0;
  left: 0;
  width: 50vw;
  height: 3px;
  background-color: #1890ff;
  border-radius: 1.5px;
  animation: myfirst 1.55s ease-in-out 0s infinite;
  -moz-animation: myfirst 1.55s ease-in-out 0s infinite;
  -webkit-animation: myfirst 1.55s ease-in-out 0s infinite;
  -o-animation: myfirst 1.55s ease-in-out 0s infinite;
}

@keyframes myfirst {
  0% {
    left: -50vw;
  }
  100% {
    left: 100vw;
  }
}

@-moz-keyframes myfirst {
  0% {
    left: -50vw;
  }
  100% {
    left: 100vw;
  }
}

@-webkit-keyframes myfirst {
  0% {
    left: -50vw;
  }
  100% {
    left: 100vw;
  }
}

@-o-keyframes myfirst {
  0% {
    left: -50vw;
  }
  100% {
    left: 100vw;
  }
}
// routerLoading.js

function show () {
  let div = document.createElement('div')
  div.id = 'routerLoading'
  document.body.appendChild(div)
}

function hide () {
  let dom = document.getElementById('routerLoading')
  if (dom) dom.remove()
}

export default {
  show,
  hide
}

添加loading

// login.js

import RouterLoad from 'tools/routerLoading'

// 懒加载
const Login = resolve => {
  // require之前开启loading
  RouterLoad.show()
  require(['@/components/login/Login'], component => {
  	// require结束后关闭loading
    RouterLoad.hide()
    resolve(component)
  })
}

export default [
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

你可能感兴趣的:(vue)