场景:在app.vue中,添加一个全局图标,有几个页面不展示,在进入不展示的页面刷新时,会闪一下图标,
原因是:路由对象初始化是异步的,页面刚加载一瞬间 meta/path 都还没准备好 。route.path 是 undefined,条件为 false,不渲染。
html
<template>
<RouterView />
<div v-if="routerReady && !arr.includes(route.path)" ref="elfRef" class="elfBox">
<p class="iconBox" @click="changeIcon"><el-icon color="red" size="16"><Remove /></el-icon></p>
<img src="@/assets/pcs/elf.gif" alt="">
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, } from 'vue'
import { useRouter, useRoute, RouterView } from 'vue-router'
const router = useRouter()
const route = useRoute()
const elfRef = ref(null)
const isFold = ref(false)
const routerReady = ref(false)
const arr = ['/login','/pcsksh']
// 解决页面刷新后,route.path为 undefined, 导致精灵闪一下
router.isReady().then(()=>{
routerReady.value = true
})
const changeIcon = ()=>{
isFold.value = !isFold.value
if(isFold.value){
elfRef.value.style.cssText = 'transform: translateX(60px) rotate(-90deg);'
}else{
elfRef.value.style.cssText = 'transform: translateX(0px) rotate(0deg);'
}
}
</script>
<style scoped lang="scss">
.elfBox{
position: fixed;
bottom: 9%;
right: 10px;
transform: translateX(0px) rotate(0deg);
transition: transform .3s ease;
.iconBox{
display: inline-block;
position: absolute;
right: 4%;
top: 6%;
}
}
</style>