Ⅰ、前言
- 当我们每次打卡页面,切换路由,甚至于异步组件,都会有一个等待的时间 ;
- 为了不白屏,提高用户体验,添加一个
loading
过度动画是 非常 常见的 ; - 那么这几种场景我们应该把
loading
加在哪里呢 ?
文章目录
- Ⅰ、前言
- Ⅱ、vue3 常见过度
- 1、 首次打开页面时 loading
- 2、 路由切换时、异步组件 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实例创建完成,通过
.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
: 过度态 ( 设置 隐藏 => 显示 过度的时间等参数)
anime-leave-active
: 过度态 ( 设置 显示 => 隐藏 过度的时间等参数)
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 性能优化总汇 ------------------------------------------------------------------------------------------------🎁
🎁Ⅱ. vue2.7 过度指南 ----------------------------------------------------------------------------------------------------🎁
🎁Ⅲ. 升级vue3问题总汇 -------------------------------------------------------------------------------------------------🎁
🎁Ⅳ. vue3 配置 JSX语法 ------------------------------------------------------------------------------------------------🎁
🎁🎁 🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁 🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁🎁