首页 > 解决方案 > How to display a component when page is loading in nuxt

问题描述

I am quite new to nuxt, and I need help here.

async asyncData({ params, route }) {
    const { data } = await axios.get(
      `${process.env.baseUrl}/homes/?search=${
        params.search
      }&home_status=${1}`
    )
    return {
      homes: data.results,
    }
  }

I am trying to populate my component with data(using asyncData), but I want my skeleton loader to show if my page is loading. How do I do that in nuxt? Here is the code for my skeleton loader;

 <template>
    <div class="placeholder-container">
      <div class="placeholder wave">
        <div class="square"></div>
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
      </div>
    </div>
</template>
<style scoped>
.placeholder-container {
  width: 35rem;
  margin: 15px auto 15px auto;
}

.placeholder {
  padding: 10px;
  width: 100%;
  // border: 1px solid lightgrey;
  display: flex;
  flex-direction: column;
}

.placeholder div {
  background: #e8e8e8;
}

.placeholder .square {
  width: 100%;
  height: 22rem;
  border-radius: 1rem;
  margin: 0 0 10px;
}

.placeholder .line {
  height: 12px;
  margin: 0 0 10px 0;
}
.placeholder .line:nth-child(2) {
  width: 120px;
}
.placeholder .line:nth-child(3) {
  width: 180px;
}
.placeholder .line:nth-child(4) {
  width: 150px;
}

.placeholder.wave div {
  animation: wave 1s infinite linear forwards;
  -webkit-animation: wave 1s infinite linear forwards;
  background: #f6f7f8;
  background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
  background-size: 800px 104px;
}

@keyframes wave {
  0% {
    background-position: -468px 0;
  }
  100% {
    background-position: 468px 0;
  }
}

@-webkit-keyframes wave {
  0% {
    background-position: -468px 0;
  }
  100% {
    background-position: 468px 0;
  }
}
</style>

What I normally do without using nuxt, is to create a data variable(loading=true), and change it to false after I finish making the api call, but since asyncData runs in the server, how do I make that work? I will also appreciate it if there is a better way of doing something like this

标签: vue.jsnuxt.jsserver-side-rendering

解决方案


占位符

要在加载期间在特定页面上显示占位符组件,请切换asyncDatafetchhook,它会在完成时公开$fetchState.pending设置为的标志true

<template>
  <div>
    <MyLoading v-if="$fetchState.pending" />
    <MyContent v-else :posts="posts" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      posts: []
    }
  },
  async fetch() {
    const { data } = await this.$axios.get(...)
    this.posts = data
  }
}
</script>

自定义加载进度条

Nuxt 提供了一个默认的加载进度条,在页面加载时显示在应用程序的顶部。您可以自定义进度条的外观

// nuxt.config.js
export default {
  loading: {
    color: 'blue',
    height: '5px'
  }
}  

或者您可以指定自己的自定义加载组件

// nuxt.config.js
export default {
  loading: '~/components/MyLoading.vue'
}

演示


推荐阅读