Vue中的異步組件函數(shù)實現(xiàn)代碼
具體代碼如下所示:
export default new Router({ routes: [ { path: '/live', name: 'live', component: () => import('@/view/live/live.vue') } ] })
上面的代碼是很常見的router代碼分割,只在代碼路由為live才會去加載live.vue
但這樣在live.vue獲取的過程將是一片空白,什么也沒有,體驗不好, 利用vue提供的異步組建可以解決
新建一個 loadable.vue
<template> <index></index> </template> <script> import LoadingComponent from './load.vue' // LoadingComponents是 live.vue為獲取前展示的內(nèi)容 export default { components: { index: () => ({ component: import('@/view/live/live.vue'), // 異步組件加載時使用的組件 loading: LoadingComponent, // 展示加載時組件的延時時間。默認值是 200 (毫秒) delay: 200, // 如果提供了超時時間且組件加載也超時了, // 則使用加載失敗時使用的組件。默認值是:`Infinity` timeout: 3000 }) } } </script>
然后修改router.js
export default new Router({ routes: [ { path: '/live', name: 'live', component: import('loadable.vue') } ] })
這樣在獲取到live.vue之前就會有自定義的loading展示了
但是路由很多, 我們不可能每個路由都寫一個 loadable.vue, 所以編寫一個函數(shù)來解決
新建一個 loadable.js
import LoadingComponent from './load.vue' export default (asyncComponent) => { const Com= () => ({ // 這里vue官網(wǎng)可以知道具體有哪些參數(shù)可以設(shè)置 // https://cn.vuejs.org/v2/guide/components-dynamic-async.html#%E5%A4%84%E7%90%86%E5%8A%A0%E8%BD%BD%E7%8A%B6%E6%80%81 component: asyncComponent(), loading: LoadingComponent }) return { render (h) { return h(Com, {}) } } }
然后修改一下router.js
import loadable from 'loadable.js' export default new Router({ routes: [ { path: '/live', name: 'live', component: loadable (() => import('@/view/live/live.vue')) } ] })
這樣一個極簡的vue異步函數(shù)就完成了
總結(jié)
以上所述是小編給大家介紹的Vue中的異步組件函數(shù)實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
vue使用數(shù)組splice方法失效,且總刪除最后一項的問題及解決
這篇文章主要介紹了vue使用數(shù)組splice方法失效,且總刪除最后一項的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue+iview如何實現(xiàn)拼音、首字母、漢字模糊搜索
這篇文章主要介紹了vue+iview如何實現(xiàn)拼音、首字母、漢字模糊搜索,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04Vue中靈活拖拽的前端神器VueDraggablePlus的用法詳解
這篇文章主要介紹了一款功能強大、靈活易用的前端組件VueDraggablePlus,作為前端工程師,我們經(jīng)常會遇到需要實現(xiàn)拖拽功能的場景,而VueDraggablePlus正是為了解決這一痛點而誕生的,讓我們一起來看看它的特點和用法吧2024-03-03Vue中Table組件行內(nèi)右鍵菜單實現(xiàn)方法(基于 vue + AntDesign)
這篇文章主要介紹了Vue中Table組件行內(nèi)右鍵菜單實現(xiàn)方法,該項目是基于 vue + AntDesign的,具體實例代碼給大家介紹的非常詳細 ,需要的朋友可以參考下2019-11-11