vue3+vite全局loading

vue3+vite全局loading

j-loading.vue组件

<template>
  <transition enter-active-class="animate__animated animate__fadeIn"
              leave-active-class="animate__animated animate__fadeOut">
    <div class="root-box" v-if="show">
      <div class="wrap">
        <img src="../../assets/img/loading.gif"/>
      </div>
    </div>
  </transition>
</template>

<script setup>
import {ref} from "vue"
const show = ref(false)

const showLoading = () => {
  show.value = true
}
const hideLoading = (callback) => {
  show.value = false
  callback && setTimeout(() => callback(), 500)
}

defineExpose({
  show,
  showLoading,
  hideLoading
})
//指令使用
// v-jwq-loading="jLoading"

//函数使用
// import {getCurrentInstance} from 'vue'
// // 获取当前实例
// const {proxy} = getCurrentInstance()
// 全局显示自定义loading
// const showJwqLoading = () => {
//   proxy.$showLoading()
//   setTimeout(() => {
//     proxy.$hideLoading()
//   }, 2000)
// }
</script>

<style scoped lang="scss">
.animate__animated.animate__fadeIn {
  --animate-duration: 0.5s;
}

.animate__animated.animate__fadeOut {
  --animate-duration: 0.5s;
}

.root-box {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: 0;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 2000;
  display: flex;
  justify-content: center;
  align-items: center;

  .wrap {
    width: 300px;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;

    img {
      width: 100%;
      //transform: scale(2.5);
    }
  }
}
</style>

jLoadding.js

import {createVNode, render, cloneVNode} from "vue"
import jLoading from "./j-loading.vue"

export default {
    install(app) {
        // 使用vue底层的createVNode方法将组件渲染为虚拟节点
        const VNode = createVNode(jLoading)
        // 使用render函数将组件挂载到body中
        render(VNode, document.body)
        // 定义全局方法设置组件的显示和隐藏
        app.config.globalProperties.$showLoading = VNode.component.exposed.showLoading
        app.config.globalProperties.$hideLoading = VNode.component.exposed.hideLoading

        const weakMap = new WeakMap()

        // 自定义Loading指令
        app.directive("jwq-loading", {
            mounted(el) {
                if (weakMap.get(el)) return
                //  记录当前绑定元素的position
                weakMap.set(el, window.getComputedStyle(el).position)
            },
            updated(el, binding) {
                const oldPosition = weakMap.get(el);
                // 如果不是position: relative或者absolute,就设置为relative
                // 这里的目的是确保loading组件正确覆盖当前绑定的元素
                if (oldPosition !== 'absolute' && oldPosition !== 'relative') {
                    el.style.position = 'relative'
                }
                // 克隆一份loading元素,
                // 作用是当页面上有多个zx-loading时,每个dom都维护一份属于自己的loading,不会冲突
                const newVNode = cloneVNode(VNode)
                // 挂载当前节点
                render(newVNode, el)
                // 判断绑定的值
                if (binding.value) {
                    newVNode.component.exposed.showLoading()
                } else {
                    newVNode.component.exposed.hideLoading(() => {
                        // 还原布局方式
                        el.style.position = oldPosition
                    })
                }
            }
        })
    }
}

main.js

import jLoading from "./components/j-loading/jLoading.js"
// 引入自定义的全局Loading
app.use(jLoading)

全局设置请求

import jLoading from "@/components/j-loading/j-loading.vue"
import {createVNode, render} from "vue";
const VNode = createVNode(jLoading)
// 使用render函数将组件挂载到body中
render(VNode, document.body)
//开启加载
const showLoading=()=>{
  VNode.component.exposed.showLoading()
}
//关闭加载
const hideLoading=()=>{
  VNode.component.exposed.hideLoading()
}
//如get请求演示
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    showLoading()//开启loading
    axios.get(url, {
      params: params
    })
      .then(response => {
        hideLoading()//关闭loading
        resolve(response);
      })
      .catch(err => {
        reject(err)
      })
  })
}
Vue 3中,可以使用Vite构建工具来快速搭建项目。下面是一个简单的示例,演示如何使用Vite和Axios进行二次封装。 首先,确保已经安装了Vite和Axios。 1. 创建一个新的Vue项目: ```bash # 使用Vite创建新项目 npm init vite my-project cd my-project npm install ``` 2. 安装Axios: ```bash npm install axios ``` 3. 创建一个`api`文件夹,并在其中创建一个`request.js`文件,用于封装Axios的请求逻辑: ```javascript import axios from &#39;axios&#39; // 创建自定义Axios实例 const instance = axios.create({ baseURL: &#39;http://api.example.com&#39;, // 设置接口基本路径 timeout: 5000 // 设置请求超时时间 }) // 请求拦截器 instance.interceptors.request.use(config => { // 在发送请求之前做一些处理,例如添加认证信息等 return config }, error => { return Promise.reject(error) }) // 响应拦截器 instance.interceptors.response.use(response => { // 在接收到响应数据之前做一些处理,例如统一处理错误码等 return response.data }, error => { return Promise.reject(error) }) export default instance ``` 4.Vue组件中使用封装好的Axios实例: ```javascript import request from &#39;@/api/request&#39; export default { methods: { fetchData() { request.get(&#39;/data&#39;) .then(response => { // 处理返回的数据 }) .catch(error => { // 处理请求错误 }) } } } ``` 使用以上方法,我们可以将Axios进行二次封装,在Vue项目中更方便地使用。你还可以根据实际需求,进一步扩展封装的功能,例如处理全局错误、统一处理Loading状态等。 **
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值