Vue3 全局 Loading 指令实现:简单易用,提升用户体验
以下是一个可能的实现:
- 在 'src/directives/loading.js' 中定义一个名为 'loading' 的指令:
import { createApp } from 'vue'
import LoadingComponent from '../components/Loading.vue'
const app = createApp(LoadingComponent)
app.mount(document.createElement('div'))
export default {
mounted(el, binding) {
const isLoading = binding.value
const div = app._container?.firstChild
if (isLoading) {
el.appendChild(div)
} else {
el.removeChild(div)
}
}
}
- 在 'src/main.js' 中注册该指令:
import { createApp } from 'vue'
import App from './App.vue'
import loadingDirective from './directives/loading'
const app = createApp(App)
app.directive('loading', loadingDirective)
app.mount('#app')
- 在需要使用 loading 的组件中使用该指令:
<template>
<div v-loading='isLoading'>
<!-- your content -->
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false
}
},
methods: {
fetchData() {
this.isLoading = true
// do your async operation
.then(() => {
// do something
})
.finally(() => {
this.isLoading = false
})
}
}
}
</script>
- 在 'src/components/Loading.vue' 中定义 loading 组件的样式和内容:
<template>
<div class='loading-container'>
<div class='loading'></div>
</div>
</template>
<style>
.loading-container {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(255, 255, 255, 0.8);
z-index: 9999;
}
.loading {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
border: 4px solid #ccc;
border-top-color: #333;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
原文地址: https://www.cveoy.top/t/topic/n4an 著作权归作者所有。请勿转载和采集!