我正在尝试 VueJS。我制作了一个非常轻量级的“应用程序”,其中只有两个视图:“Home”和“MineSweeper”。在 App.vue 中,我创建了一个导航栏,其中包含指向这些视图的按钮,并使用 RouterView 组件显示了这些视图。
我尝试使用 Transition 组件,这样当主页加载时以及每当我在视图之间切换时,就会有淡入淡出效果。
这是我的App.vue:
<template>
<div class="nav">
<RouterLink to="/" class="navIcon">Home</RouterLink>
<RouterLink to="/mine" class="navIcon">Minesweeper</RouterLink>
</div>
<RouterView v-slot="{ Component }">
<Transition name="fade" mode="out-in">
<component :is="Component" />
</Transition>
</RouterView>
</template>
<script lang="ts">
/* just boilerplate script with defineComponent. Its practically empty*/
</script>
<style scoped>
.nav {
width: 100vw;
height: 5vh;
background-color: black;
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
}
.navIcon {
border: none;
background-color: black;
color: white;
text-decoration: none;
padding-left: 20px;
margin-bottom: 10px;
font-size: 30px;
}
.fade-enter-active,
.fade-leave-active {
transition: 1500ms ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
当我最初加载主页时,淡入效果起作用。当我切换到扫雷视图时,它起作用了。当我在扫雷视图上并尝试切换回主视图时,尽管我将过渡设置为 1500 毫秒,但仍需要约 25 秒的时间。无论转换是 1 毫秒还是 10000 毫秒,都需要约 25 秒。
有什么想法吗?您还需要更多文件吗?
提前致谢!
编辑:
我检查了开发工具中的性能。它只显示 25 秒的丢帧。然后我突然想到,在扫雷视图中,我制作了一个动画背景,需要 25 秒然后重新启动:
.body {
height: 95dvh;
background: linear-gradient(-45deg, #692612, #860b3a, #092499,
#0f965e);
background-size: 400% 400%;
animation: gradient 25s ease infinite;
}
@keyframes gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
因此,应用程序似乎淡出,然后等待动画的完整迭代,然后淡入新视图。如果我只禁用动画,它就可以正常工作。现在我只需要弄清楚如何让它与动画一起工作......
好吧,正如我所说,问题出在 25 秒的背景动画上。 为了使其工作,我必须对受动画影响的 HTML 元素(在本例中为 div.body)进行动态类绑定:
<div class="body" :class="{ 'mine-sweep-animation': isActive }">
<-- rest of the template -->
为此 CSS 进行了更改:
.body {
height: 95dvh;
background: linear-gradient(-45deg, #692612, #860b3a, #092499, #0f965e);
background-size: 400% 400%;
}
.mine-sweep-animation {
animation: gradient 25s ease infinite;
}
// @keyframes stays the same
有一个“isActive”变量绑定到 div.body 类。只需在defineComponent的data部分将其设置为true,并在通过beforeRouteLeave离开组件时将其设置为false即可:
export default defineComponent({
name: "MineSweeper",
data() {
return {
// bunch of other data
isActive: true,
};
},
computed: {
// bunch of computed parameters
},
methods: {
// bunch of methods
},
beforeRouteLeave() {
this.isActive = false;
},
});
这将使一切顺利。唯一的缺点是,当我变回“Home”视图时,beforeRouteLeave 会立即触发,因此动画在淡出过程中停止,因此可以看到动画重置为 0 秒状态,这不是最漂亮的,但是哦,好吧,不能拥有一切。