How to display a “loading” animation while a lazy-loaded route component is being loaded?

前端 未结 3 2055
不知归路
不知归路 2020-12-13 00:38

I have split my app into multiple chunks with webpack\'s code splitting feature so that the entire application bundle isn\'t downloaded when the user visits my webpage.

3条回答
  •  感动是毒
    2020-12-13 01:26

    You can use navigation guards to activate/deactivate a loading state that shows/hides a loading component:

    If you would like to use something like "nprogress" you can do it like this:

    http://jsfiddle.net/xgrjzsup/2669/

    const router = new VueRouter({
      routes
    })
    
    router.beforeEach((to, from, next) => {
      NProgress.start()
      next()
    })
    router.afterEach(() => {
      NProgress.done()
    })
    

    Alternatively, if you want to show someting in-place:

    http://jsfiddle.net/h4x8ebye/1/

    Vue.component('loading',{ template: '
    Loading!
    '}) const router = new VueRouter({ routes }) const app = new Vue({ data: { loading: false }, router }).$mount('#app') router.beforeEach((to, from, next) => { app.loading = true next() }) router.afterEach(() => { setTimeout(() => app.loading = false, 1500) // timeout for demo purposes })

    Then in the template:

    
      
    

    That could also be easily encapsulated in a very small component instead of using the $root component for the loading state.

提交回复
热议问题