以下是一个可能的实现:

  1. 在 '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)
    } 
  }
}
  1. 在 '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')
  1. 在需要使用 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>
  1. 在 '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>
Vue3 全局 Loading 指令实现:简单易用,提升用户体验

原文地址: https://www.cveoy.top/t/topic/n4an 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录