VUE2局部触发全局loading(provide/inject)

当前有个需求,是路由内部某个组件发生某些操作时,开启/关闭全局(整个页面)的loading效果。

1. 需求分析

在收到这个需求时,考虑到关键点在于跨组件通信,于是想到以下这些方法并进行分析可行性:

序号方法适用场景是否可行备注
1props、$emitV2、V3,直接父子组件
2Event BusV2、V3,跨组件EventBus.$ emit发送消息,EventBus.$ on监听接收消息
3VuexV2,跨组件手动监听vuex变化
4provide、injectV2、V3, 跨组件
5slotsV2、V3,直接父子组件
6Ref / ReactiveV3,直接父子组件
7useAttrsV3,直接父子组件
8PiniaV3,跨组件手动监听pinia变化

通过以上分析,认为provide/inject的方式比较方便快捷(更熟悉),于是通过此方式实现。

2. 实现

(1)app.vue

全局loading状态、方法控制

<template>
  <div id="app" v-loading="globalLoading">
    <router-view/>
  </div>
</template>

<script>
export default  {
  name:  'App',
  provide(){
    return {
      hideGLoading: this.hideGLoading, // 全局loading关闭方法
      showGLoading: this.showGLoading, // 全局loading显示方法
    }
  },
  data(){
    return{
      globalLoading: false, // 全局loading状态
    }
  },
  methods:{
    hideGLoading() {
      this.globalLoading = false;
    },
    showGLoading() {
      this.globalLoading = true;
    }
  }
}
</script>

(2)局部组件

handleGather 时触发全局loading显示,接口请求完触发全局loading关闭。

	inject: ['hideGLoading','showGLoading'], // 全局loading
 	/** methods 操作 */
   handleGather(row) {
     this.showGLoading();
     getAPIData().then(res => {
         // this.gatherInfo = res.data; 接口数据操作
     }).finally(() => {
         this.hideGLoading();
     })
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值