Vue3 異步組件 suspense使用詳解
vue在解析我們的組件時, 是通過打包成一個 js 文件,當我們的一個組件 引入過多子組件是,頁面的首屏加載時間 由最后一個組件決定 優(yōu)化的一種方式就是采用異步組件 ,先給慢的組件一個提示語或者 骨架屏 ,內容回來在顯示內容
結合elementui 使用
代碼
<template> <div class="layout"> <h1>suspense</h1> <Suspense> <template #default> <sus></sus> </template> <template #fallback> <copyVue/> </template> </Suspense> </div> </template> <script lang="ts" setup> import { defineAsyncComponent } from "vue"; import copyVue from "./sus/copy.vue"; let sus = defineAsyncComponent(() => import("./sus/index.vue")); </script> <style scoped lang="scss"> $bg:#ccc; .layout{ width: 800px; height: 400px; background-color: $bg; margin: auto; } </style>
引入 defineAsyncComponent 定義異步組件 ,這個api 接收 一個 一個函數 ,函數返回值 為 需要 后來顯示的組件 , copyVue 為預先顯示的組件 或者自定義內容
<Suspense> <template #default> <sus></sus> </template> <template #fallback> <copyVue/> </template> </Suspense>
使用 suspense 內置組件 在該組件內 使用 命名插槽 官方 定義的
#default 放后來顯示的組件
#fallback 放置 預先顯示的內容
要想組件變成異步 組件 可以使用 頂層 await 技術 即 不用再 async 函數內使用 那個該組件就變成 異步組件 代碼
<template> <div class="sus"> <img class="img" :src="res.url" alt=""> <h1 class="posi">{{res.name }}</h1> <h1 class="posi">{{ res.des }}</h1> </div> </template> <script lang="ts" setup> import axios from 'axios' import './com.scss' let fn = ()=>{ return new Promise( (resolve,reject)=>{ setTimeout(async() => { resolve(axios.get('/data.json')) }, 2000); }) } let {data:{data:res}}:any = await fn() console.log(res); </script> <style scoped lang='scss'> .sus{ width: 100%; height: 200px; background-color: #999; } </style>
copyvue
<template> <div v-loading="loading" element-loading-text="加載中..." element-loading-background="rgba(122, 122, 122, 0.8)" class="sus"> </div> </template> <script lang="ts" setup> import axios from 'axios' import { ref } from 'vue' const loading = ref(true) </script> <style scoped lang='scss'> .sus{ width: 100%; height: 200px; } </style>
scss
.posi{ height: 50px; background-color: rgb(209, 136, 136); margin-top: 20px; } .img{ width: 30px; height: 30px; background-color: rgb(113, 52, 52); }
public 下的 data.json
{ "data":{ "name":"你好世界", "url":"./favicon.ico", "des":"世界是個荒原" } }
public 下的 內容 回當成 服務的 '/xxx' 請求路徑 get可以請求 到文件內容
http://localhost:5173/data.json
到此這篇關于Vue3 異步組件 suspense的文章就介紹到這了,更多相關Vue3 異步組件 suspense內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
element-ui 限制日期選擇的方法(datepicker)
本篇文章主要介紹了element-ui 限制日期選擇的方法(datepicker),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05Vue.js中自定義Markdown插件實現References解析(推薦)
本文主要寫的是,如何編寫一個插件來解析<references>標簽,并將其轉換為HTML,這種方法可以應用于其他自定義標簽和功能,為Vue.js應用程序中的Markdown渲染提供了極大的靈活性,感興趣的朋友跟隨小編一起看看吧2024-07-07Vue實現導出Excel表格文件提示“文件已損壞無法打開”的解決方法
xlsx用于讀取解析和寫入Excel文件的JavaScript庫,它提供了一系列的API處理Excel文件,使用該庫,可以將數據轉換Excel文件并下載到本地,適用于在前端直接生成Excel文件,這篇文章主要介紹了Vue實現導出Excel表格,提示文件已損壞,無法打開的解決方法,需要的朋友可以參考下2024-01-01