当前位置:首页 > VUE

vue 怎么实现loading

2026-03-09 23:06:10VUE

实现 Loading 的方法

在 Vue 中实现 Loading 效果可以通过多种方式完成,以下是几种常见的方法:

全局 Loading 组件

创建一个全局的 Loading 组件,通过 Vuex 或事件总线控制其显示与隐藏。在需要的地方调用相应的方法即可。

// Loading.vue
<template>
  <div v-if="isLoading" class="loading-overlay">
    <div class="loading-spinner"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isLoading: false
    }
  },
  methods: {
    show() {
      this.isLoading = true
    },
    hide() {
      this.isLoading = false
    }
  }
}
</script>

使用第三方库

许多第三方库如 element-uivant 等提供了现成的 Loading 组件,可以直接使用。

// 使用 element-ui 的 Loading
import { Loading } from 'element-ui'

let loadingInstance = Loading.service({ fullscreen: true })
// 关闭 Loading
loadingInstance.close()

路由守卫中实现 Loading

在路由切换时显示 Loading,确保页面加载完成后再隐藏。

// router.js
router.beforeEach((to, from, next) => {
  store.commit('setLoading', true)
  next()
})

router.afterEach(() => {
  store.commit('setLoading', false)
})

HTTP 拦截器中实现 Loading

在发送 HTTP 请求时显示 Loading,请求完成后隐藏。

// axios 拦截器
axios.interceptors.request.use(config => {
  store.commit('setLoading', true)
  return config
})

axios.interceptors.response.use(response => {
  store.commit('setLoading', false)
  return response
}, error => {
  store.commit('setLoading', false)
  return Promise.reject(error)
})

自定义 Loading 动画

可以通过 CSS 或 SVG 实现自定义的 Loading 动画,增强用户体验。

.loading-spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #3498db;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

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

结合异步操作

在异步操作如 async/await 中控制 Loading 的显示与隐藏。

vue 怎么实现loading

methods: {
  async fetchData() {
    this.isLoading = true
    try {
      const response = await axios.get('/api/data')
      this.data = response.data
    } catch (error) {
      console.error(error)
    } finally {
      this.isLoading = false
    }
  }
}

通过以上方法,可以根据具体需求在 Vue 项目中灵活实现 Loading 效果。

标签: vueloading
分享给朋友:

相关文章

vue实现生成二维码

vue实现生成二维码

使用qrcode.vue库生成二维码 安装qrcode.vue库: npm install qrcode.vue --save 在Vue组件中使用: <template> <…

vue实现换行

vue实现换行

Vue 中实现换行的几种方法 在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法: 使用 HTML 的 <br> 标签 在模板中直接使用 <br…

vue 实现树状

vue 实现树状

Vue 实现树状结构的方法 递归组件实现树状结构 递归组件是 Vue 中实现树状结构的常见方法。通过组件自身调用自身,可以轻松构建多层级树状结构。 <template> <ul…

vue实现datalist

vue实现datalist

使用 Vue 实现 HTML5 的 datalist 功能 HTML5 的 <datalist> 元素提供了一种自动完成输入框的功能,允许用户在输入时从预定义的选项列表中选择。以下是几种在…

vue实现多选

vue实现多选

Vue 实现多选功能 在 Vue 中实现多选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定到一个数组,可以实现多选功能。适用于复选框组(…

vue jwt实现

vue jwt实现

Vue JWT 实现方法 安装依赖 确保项目中安装了 jsonwebtoken(后端)和 axios(前端)。若使用 Vue 3,可搭配 vue-router 和 pinia(或 vuex)管理状态。…