当前位置:首页 > VUE

vue 实现loading

2026-03-27 21:32:55VUE

实现Loading效果的几种方法

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

使用CSS动画实现基础Loading

通过CSS定义旋转动画,结合Vue的条件渲染(v-if/v-show)控制显示状态:

<template>
  <div v-if="isLoading" class="loading-spinner"></div>
</template>

<style>
.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

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

使用第三方库(如Element UI)

UI框架通常提供现成的Loading组件:

vue 实现loading

import { Loading } from 'element-ui'

// 开启loading
let loadingInstance = Loading.service({
  lock: true,
  text: '加载中',
  spinner: 'el-icon-loading',
  background: 'rgba(0, 0, 0, 0.7)'
})

// 关闭loading
loadingInstance.close()

全局Loading状态管理

结合Vuex实现全局Loading状态控制:

// store.js
const store = new Vuex.Store({
  state: {
    isLoading: false
  },
  mutations: {
    setLoading(state, isLoading) {
      state.isLoading = isLoading
    }
  }
})

// 组件中使用
<template>
  <div>
    <spinner v-if="$store.state.isLoading"/>
    <main-content v-else/>
  </div>
</template>

路由导航守卫控制

在页面切换时显示Loading:

vue 实现loading

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

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

自定义指令实现

创建v-loading指令自动处理加载状态:

Vue.directive('loading', {
  bind(el, binding) {
    const spinner = document.createElement('div')
    spinner.className = 'loading-spinner'
    el.appendChild(spinner)
    spinner.style.display = binding.value ? 'block' : 'none'
  },
  update(el, binding) {
    const spinner = el.querySelector('.loading-spinner')
    if (spinner) {
      spinner.style.display = binding.value ? 'block' : 'none'
    }
  }
})

请求拦截器集成

在axios拦截器中自动管理Loading状态:

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)
  }
)

每种方法适用于不同场景,可根据项目需求选择合适的方式或组合使用。全局状态管理适合SPA应用,而局部Loading更适合组件级加载控制。

标签: vueloading
分享给朋友:

相关文章

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

实现vue datepicker

实现vue datepicker

安装依赖 使用 vue-datepicker 或第三方库如 v-calendar 或 vue2-datepicker。以 vue2-datepicker 为例: npm install vue2…

vue实现发帖

vue实现发帖

使用 Vue 实现发帖功能 前端实现 创建发帖表单组件,包含标题和内容输入框,以及提交按钮。使用 v-model 绑定表单数据。 <template> <div>…

lua 实现vue

lua 实现vue

在 Lua 中实现类似 Vue 的响应式框架需要模拟 Vue 的核心功能,包括数据绑定、模板渲染和依赖追踪。以下是实现的关键思路和代码示例: 响应式数据绑定 使用 Lua 的 __index 和 _…

vue实现github

vue实现github

Vue 实现 GitHub 相关功能 创建 GitHub API 请求 在 Vue 项目中,可以使用 axios 或 fetch 与 GitHub API 进行交互。需要在 GitHub 上创建个人访…

自实现vue

自实现vue

实现 Vue 的核心功能 要实现一个简化版的 Vue,需要理解其核心功能:数据响应式、模板编译、虚拟 DOM 和组件系统。以下是关键步骤的分解: 数据响应式 Vue 使用 Object.define…