我正在尝试在 Vue JS 中创建一个启动屏幕(加载屏幕),该屏幕在几秒钟后消失,显示我的默认 View 。我尝试了几种方法,但都无法发挥作用。最接近的是 CodePen 上的这个例子但理想情况下,该组件不会位于 main.js 内部,而是位于其自己的组件内部。尽管如此,下面的代码将不起作用。
我的main.js如下:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.config.productionTip = false;
// FILTERS
Vue.filter('snippet', function(value) {
return value.slice(0,100);
});
Vue.component('loading-screen', {
template: '<div id="loading">Loading...</div>'
})
new Vue({
router,
store,
render: h => h(App),
data: {
isLoading: true
},
mounted () {
setTimeout(() => {
this.isLoading = false
}, 3000)
}
}).$mount("#app");
我的App.vue如下
<template>
<div id="app">
<loading-screen v-if="isLoading"></loading-screen>
<Top/>
<router-view/>
<PrimaryAppNav/>
</div>
</template>
<script>
import Top from './components/Top.vue'
import PrimaryAppNav from './components/PrimaryAppNav.vue'
export default {
name: 'app',
components: {
Top,
PrimaryAppNav
}
}
</script>
最佳答案
LoadingScreen.vue
组件可能如下所示:
<template>
<div :class="{ loader: true, fadeout: !isLoading }">
Loading ...
</div>
</template>
<script>
export default {
name: "LoadingScreen",
props: ["isLoading"]
};
</script>
<style>
.loader {
background-color: #63ab97;
bottom: 0;
color: white;
display: block;
font-size: 32px;
left: 0;
overflow: hidden;
padding-top: 10vh;
position: fixed;
right: 0;
text-align: center;
top: 0;
}
.fadeout {
animation: fadeout 2s forwards;
}
@keyframes fadeout {
to {
opacity: 0;
visibility: hidden;
}
}
</style>
请注意,加载程序需要知道加载是否完成才能淡出。您还需要在您的应用程序中检查这一点,因此它在仍需要准备数据时不会显示。否则,来自后台应用程序部分的信息可能会泄漏(例如,滚动条可能在加载屏幕上可见)。所以 App.vue
可以有这样的模板:
<template>
<div id="app">
<LoadingScreen :isLoading="isLoading" />
<div v-if="!isLoading">
...your main content here...
</div>
</div>
</template>
如果你想让 LoadingScreen div 完全消失,你需要在 App.vue
本身中管理淡出动画的状态,使其变得更加复杂(我可能会然后为 LoadingScreen 使用两个属性:isLoading
和 fadeout
,其中 fadeout
是在 LoadingScreen
中调用的回调,如下所示淡出动画完成后立即)。
我准备了一个codesandbox为您提供 LoadingScreen
内的状态管理。
关于javascript - 如何在 VueJS 中创建启动屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356211/