vue实现加载
Vue 实现加载功能的方法
使用 v-if 或 v-show 控制加载状态
通过数据绑定控制加载元素的显示与隐藏,适用于简单场景。
<template>
<div>
<div v-if="isLoading">加载中...</div>
<div v-else>加载完成的内容</div>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: true
}
},
mounted() {
setTimeout(() => {
this.isLoading = false
}, 2000)
}
}
</script>
使用异步组件实现懒加载
通过 Vue 的异步组件特性实现按需加载,优化性能。
const AsyncComponent = () => ({
component: import('./MyComponent.vue'),
loading: LoadingComponent,
error: ErrorComponent,
delay: 200,
timeout: 3000
})
集成第三方加载库
使用成熟的第三方库如 vue-loading-overlay 实现专业加载效果。
npm install vue-loading-overlay
<template>
<loading :active.sync="isLoading" :can-cancel="true"></loading>
</template>
<script>
import Loading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.css'
export default {
components: { Loading },
data() {
return {
isLoading: false
}
}
}
</script>
路由级别加载控制
在 vue-router 的导航守卫中控制全局加载状态。
router.beforeEach((to, from, next) => {
store.commit('SET_LOADING', true)
next()
})
router.afterEach(() => {
store.commit('SET_LOADING', false)
})
骨架屏技术实现
使用 vue-skeleton-webpack-plugin 生成骨架屏,提升用户体验。
// vue.config.js
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
module.exports = {
configureWebpack: {
plugins: [
new SkeletonWebpackPlugin({
webpackConfig: {
entry: './src/skeleton.js'
}
})
]
}
}
全局加载状态管理
通过 Vuex 管理全局加载状态,实现多组件共享。
// store.js
export default new Vuex.Store({
state: {
loading: false
},
mutations: {
SET_LOADING(state, status) {
state.loading = status
}
}
})
自定义指令实现加载
创建自定义指令简化加载控制逻辑。
Vue.directive('loading', {
bind(el, binding) {
if (binding.value) {
el.classList.add('loading')
} else {
el.classList.remove('loading')
}
}
})






