vue.js - 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
解决方案
占位符
要在加载期间在特定页面上显示占位符组件,请切换asyncData
到fetch
hook,它会在完成时公开$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'
}
推荐阅读
- php - PHP新手:将输入框添加到数组
- javascript - jQuery outerHeight() 产生错误的 div 高度
- swift - UIButton 的 CollectionView 问题
- animation - 补间形状位置,使其平滑地跟随光标而不是跳跃?
- html - 如何在方框中获取引导弹出框
- angular - 如何使用 ng2-charts 在角度 2 的饼图中显示数据?
- c# - 为什么我在数独求解器 C# 中不断收到 Stackoverflow 错误
- arrays - Solidworks VBA 跳过空数组
- java - 如果将Java中的JSON序列化为JSON作为对象,如何反序列化特定类型的对象?
- python-3.x - 如果有 3 个用户选择,则为单个?(我是新手)