Quasar CLI with Vite - @quasar/app-vite
當您的網站/應用程式規模較小時,您可以將所有版面/頁面/組件載入到初始捆綁包中,並在啟動時提供所有內容。但是,當您的程式碼變得複雜且具有許多版面/頁面/組件時,這樣做並不是最佳選擇,因為這將嚴重影響載入時間。幸運的是,有一種方法可以解決這個問題。
我們將介紹如何延遲載入 / 分割程式碼應用程式的各個部分,使其僅在需要時自動請求。這透過動態導入完成。讓我們先從一個範例開始,然後轉換它以使用延遲載入——我們將把這個範例重點放在載入頁面,但相同的原則可以應用於載入任何內容(資源、JSON 等)。
延遲載入路由頁面
通常會像下面這樣使用 Vue Router 呼叫靜態元件。
警告
Quasar 文件假設您已經熟悉 Vue Router。下面僅描述如何在 Quasar CLI 專案中使用它的基礎知識。如需其功能的完整列表,請訪問 Vue Router 文件。
import SomePage from 'pages/SomePage'
const routes = [
{
path: '/some-page',
component: SomePage
}
]
content_paste
現在讓我們更改這個,並使用動態導入使頁面僅在需要時載入
const routes = [
{
path: '/some-page',
component: () => import('pages/SomePage')
}
]
content_paste
很簡單吧?這樣做的目的是為 /src/pages/SomePage.vue
建立一個單獨的區塊,然後僅在需要時載入。在這種情況下,當使用者訪問 '/some-page' 路由時。
延遲載入元件
通常你會導入一個元件,然後將其註冊到頁面、佈局或元件。
<script>
import SomeComponent from 'components/SomeComponent'
export default {
components: {
SomeComponent,
}
}
</script>
content_paste
現在讓我們更改這個,並使用動態導入使元件僅在需要時載入
<script>
import { defineAsyncComponent } from 'vue'
export default {
components: {
SomeComponent: defineAsyncComponent(() => import('components/SomeComponent')),
}
}
</script>
content_paste
即時延遲載入
如您在上面注意到的,我們正在使用動態導入 (import('..resource..')
) 而不是常規導入 (import Resource from './path/to/resource'
)。動態導入本質上是返回一個你可以使用的 Promise
import('./categories.json')
.then(categories => {
// hey, we have lazy loaded the file
// and we have its content in "categories"
})
.catch(() => {
// oops, something went wrong...
// couldn't load the resource
})
content_paste
使用動態導入而不是常規導入的一個優點是導入路徑可以在運行時確定
import('pages/' + pageName + '/' + idWithExtension)
content_paste
使用 Vite 導入
動態導入語句
const importList = import.meta.glob('./pages/*.vue')
const startIndex = '/pages/'.length
const routes = Object.keys(importList).map(key => {
return {
path: key.substring(startIndex, key.length - 4),
component: importList[ key ]
}
})
content_paste
其他導入選項
有關使用 Vite 導入資源的更多資訊,請參閱 此處。