uniapp loading如何实现页面加载效果

在uniapp中,如何使用loading实现页面加载效果?官方文档提到了uni.showLoading,但不知道如何在页面跳转时显示加载动画。尝试了在onLoad生命周期里调用,但有时候会出现闪烁或者不显示的情况。有没有更稳定的实现方式?另外,能否自定义loading的样式和文字提示?

2 回复

在uniapp中实现页面加载效果,可使用以下方法:

  1. 使用uni.showLoading()显示加载提示
uni.showLoading({
  title: '加载中'
})
  1. 页面加载完成后调用uni.hideLoading()关闭

  2. 也可在页面中使用<view v-if="loading">加载中...</view>配合数据绑定实现自定义loading效果

  3. onLoad生命周期中开始加载,数据获取完成后结束加载


在 UniApp 中,可以通过以下方法实现页面加载效果:

1. 使用内置 Loading 组件

<template>
  <view>
    <!-- 页面内容 -->
    <view v-if="!loading">页面内容</view>
    
    <!-- 加载中状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: true
    }
  },
  onLoad() {
    // 模拟数据加载
    this.loadData()
  },
  methods: {
    async loadData() {
      try {
        // 模拟异步请求
        await this.$http.get('/api/data')
        this.loading = false
      } catch (error) {
        this.loading = false
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style>
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200rpx;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #007AFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

2. 使用 uni.showLoading API

// 显示加载提示
uni.showLoading({
  title: '加载中...',
  mask: true
})

// 模拟数据请求
setTimeout(() => {
  // 隐藏加载提示
  uni.hideLoading()
}, 2000)

3. 结合页面生命周期

export default {
  data() {
    return {
      loading: true,
      data: null
    }
  },
  
  async onLoad() {
    await this.fetchData()
    this.loading = false
  },
  
  async onPullDownRefresh() {
    this.loading = true
    await this.fetchData()
    this.loading = false
    uni.stopPullDownRefresh()
  },
  
  methods: {
    async fetchData() {
      // 数据请求逻辑
    }
  }
}

4. 使用第三方 UI 库

如果使用 uView、ColorUI 等第三方 UI 库,可以使用它们提供的 Loading 组件:

<u-loading :show="loading" mode="circle"></u-loading>

推荐做法

  • 简单加载提示使用 uni.showLoading()
  • 复杂页面加载使用自定义 Loading 组件
  • 注意在请求完成后及时隐藏 Loading 状态
  • 添加错误处理,避免 Loading 一直显示
回到顶部