vue项目配置请求加载中效果

本文介绍了如何在Vue项目中结合Vuex管理全局加载状态。通过在main.vue中引入iView的Spin组件,并在store中定义isLoading状态,配合axios请求,动态控制加载中的显示与隐藏。在需要显示加载效果的请求中,通过传入参数控制store中的状态,实现了优雅的加载效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.main.vue引入iview Spin组件

<Content class="content-wrapper">
     <Spin fix v-show="loading">
       <Icon type="ios-loading" size="18" class="spin-load"></Icon>
       <div>加载中...</div>
     </Spin>
     <keep-alive>
       <router-view :key="$route.name"></router-view>
     </keep-alive>
   </Content>
 </Layout>
</Content>


loading() {
  return this.$store.state.isLoading;
},

2.store定义isLoading状态

export default new Vuex.Store({
    state: {
        isLoading: false,
    },
    mutations: {
        updateLoading(state, loading) {
            state.isLoading = loading
        },
    }
})

3.post请求修改store中的值

/**
 * 自定义POST请求
 * @param {string} api 请求接口名称
 * @param {Object} param 参数对象
 */
const post = function(api, param, { showLoading = false } = {}) {
    return new Promise((resolve, reject) => {
            if (showLoading) {
                store.commit('updateLoading', true)
            }
            axios({
                method: 'post',
                url: url,
                data: reqData.data
            }).then(res => {
                if (showLoading) {
                    store.commit('updateLoading', false)
                }
                //doSomeThing...
            }).catch(err => {
                if (showLoading) {
                    store.commit('updateLoading', false)
                }
                //doSomeThing...
                reject(err);
            })
    })
}

4.在需要加载中样式的请求中配置

initData() {
      this.$post("api", this.params, { showLoading: true }).then(
        (res) => {
          //doSomeThing...
        }
      );
    },

5.效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值