如何在VueJS中创建启动画面?

Al-*_*-76 0 javascript vue.js vuejs2

我试图在Vue JS中创建一个启动屏幕(加载屏幕),几秒钟后消失,显示我的默认视图。我尝试了几种方法,但都无法使用。最接近此示例的是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");
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

Nar*_*igo 5

一个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>
Run Code Online (Sandbox Code Playgroud)

请注意,加载程序需要知道是否已完成加载才能淡出。您还需要在您的应用程序中检查它,因此它仍然需要准备数据时不会显示。否则,来自后台应用程序部分的信息可能会泄漏(例如,滚动条可能在LoadingScreen上可见)。因此App.vue可以有一个这样的模板:

<template>
  <div id="app">
    <LoadingScreen :isLoading="isLoading" />
    <div v-if="!isLoading">
      ...your main content here...
    </div>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

如果要让LoadingScreen div完全消失,则需要管理淡入淡出动画App.vue本身的状态,使其更加复杂(我可能会为LoadingScreen使用两个道具,然后是:isLoadingfadeout,其中fadeout是回调LoadingScreen淡入淡出动画完成后立即调用)。

我已经为您准备了一个codeandbox,其中包含状态管理LoadingScreen