vue3如何解決各場景l(fā)oading過度(避免白屏尷尬!)
Ⅰ、前言
當我們每次打卡頁面,切換路由,甚至于異步組件,都會有一個等待的時間 ;
為了不白屏,提高用戶體驗,添加一個 loading 過度動畫是 非常 常見的 ;
那么這幾種場景我們應該把 loading 加在哪里呢 ?

Ⅱ、vue3 常見過度
針對以下 3 種情況 做了一下整理 ??
① 首次打開頁面時;
② 路由切換時;
③ 異步組件顯示時;
1、 首次打開頁面時 loading
在頁面首次打開的加載內容,是最容易的,通過根目錄 index.html文件
在 <div id='app'> 里添加內容,就是過度內容
<body>
<div id="app">
<h1>加載中......</h1>
</div>
<script type="module" src="/src/main.js"></script>
</body>
當vue實例創(chuàng)建完成,通過.mount() 方法掛載到 id='app' 的div 里,會替換掉里的loading內容;
2、 路由切換時、異步組件 loading
- 路由切換過度 需要先了解一個,
vue3的內置組件<Suspense>; <Suspense>提供2個插槽 ??;#default: 一個要加載的內容 ;#fallback: 一個加載種顯示的內容;
<Suspense> <template #default> <router-view /> </template> <template #fallback> <h1>加載中......</h1> </template> </Suspense>
同理:( 異步組件的切換 )
<template>
<Suspense>
<template #default>
<AsyncComp v-if = 'vitblie' />
</template>
<template #fallback>
<h1>加載中......</h1>
</template>
</Suspense>
<button @click='open'> 切換 </button>
</template>
<script setup>
import { defineAsyncComponent , ref } from 'vue';
const asyncComp = defineAsyncComponent(()=>important('./asyncComp.vue));
const vitblie = ref(false);
function open(){
vitblie.value = !vitblie.value;
}
</script>
異步組件也是可以使用相同的方法
Ⅲ、 添加過度動畫
添加過度動畫需要先了解 vue3 內置組件 <Component> 和 <Transition> ??
<Component>: 非常簡單只有一個 is 顯示該組件, 可以用來組件切換 如:
<template> <Component :is="visible ? TestComp : '' " /> </template>
<Transition> : 里插入的內容 顯示/隱藏 添加過度動畫 ,通過 name 屬性來拼接 class 如 :
<template> <transition name='anime'> <TestComp v-if='visblte' /> </transition> </template>
設置樣式通過 name 屬性 這里
anime-enter-active: 過度態(tài) ( 設置 隱藏 => 顯示 過度的時間等參數)anime-leave-active: 過度態(tài) ( 設置 顯示 => 隱藏 過度的時間等參數)anime-enter-from=>anime-enter-to隱藏 => 顯示 開始和結束的樣式anime-leave-from=>anime-leave-to顯示 => 隱藏 開始和結束的樣式
組合起來 ??
<template>
<router-view v-slot={ Component } >
<transition name='anime'>
<component :is="Component" />
<transition>
</router-view>
<template>
<style scoped>
.anime-enter-active,
.anime-leave-active {
transition: all 1s;
}
.anime-leave-from { transform: translateY(0); }
.anime-leave-to { transform: translateY(-100%); }
.anime-enter-from { transform: translateY(100%); }
.anime-enter-to { transform: translate(0); }
</style>
總結
到此這篇關于vue3如何解決各場景l(fā)oading過度的文章就介紹到這了,更多相關vue3各場景l(fā)oading過度解決內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue項目Element表格對應字段映射顯示方法:formatter格式化數據問題
這篇文章主要介紹了Vue項目Element表格對應字段映射顯示方法:formatter格式化數據問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
詳解解決使用axios發(fā)送json后臺接收不到的問題
這篇文章主要介紹了詳解解決使用axios發(fā)送json后臺接收不到的問題,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06

