为vue项目自动设置请求状态

在进入一个页面的时候,一般在获取数据的同时,会先显示一个 loading,等请求结束再隐藏 loading 渲染页面,只需要用一个属性去记录请求的状态,再根据这个状态去渲染页面就好了

async handler() {
    this.loading = true
    await fetch()
    this.loading = false
}
复制代码

虽然是很简单的功能,可是要处理的地方多的时候,还是很繁琐的,就想着能不能统一设置处理请求的 loading,然后页面根据 loading 的状态决定要显示的内容,就根据自己的想法做了一些封装,自动给所有 ajax 请求设置 loading 状态,主要思路是把所有请求集中到单一实例上,通过 proxy 代理属性访问,把 loading 状态提交到 storestate

安装

$ npm install vue-ajax-loading
复制代码

演示

在线demo(打开较慢)

使用

  • 配置 store 的 state 及 mutations
import { loadingState, loadingMutations } from 'vue-ajax-loading'

const store = new Vuex.Store({
    state: {
        ...loadingState
    },
    mutations: {
        ...loadingMutations
    }
})
复制代码
  • 把所有请求集中到一个对象上
import { ajaxLoading } from 'vue-ajax-loading'
import axios from 'axios'
import store from '../store' // Vuex.Store 创建的实例

axios.defaults.baseURL = 'https://cnodejs.org/api/v1'

// 把请求集中到单一对象上,如:
const service = {
    global: {
        // 全局的请求
        getTopics() {
            return axios.get('/topics')
        },
        getTopicById(id = '5433d5e4e737cbe96dcef312') {
            return axios.get(`/topic/${id}`)
        }
    },
    modules: {
        // 有命名空间的请求,命名空间就是 topic
        topic: {
            getTopics() {
                return axios.get('/topics')
            },
            getTopicById(id = '5433d5e4e737cbe96dcef312') {
                return axios.get(`/topic/${id}`)
            }
        }
    }
}

export default ajaxLoading({
    store,
    service
})
复制代码

完成以上配置之后,通过上面 export default 出来的对象去发送请求,就会自动设置请求的状态,然后可以在组件内通过 this.$store.state.loadingthis.$loading 去访问请求状态,如:

<el-button type="primary" :loading="$loading.getTopics" @click="handler1">getTopics</el-button>
<el-button type="primary" :loading="$loading.delay" @click="delay">定时两秒</el-button>
<el-button type="primary" :loading="$loading.topic.getTopics" @click="handler3">topic.getTopics</el-button>
复制代码
import api from 'path/to/api'

export default {
    methods: {
        handler1() {
            api.getTopics()
        },
        handler3() {
            api.topic.getTopics()
        },
        delay() {
            api.delay()
        }
    }
}
复制代码

Options

store

Vuex.Store 创建的实例

service

包含所有请求的对象,可以配置 globalmodules 属性

  • global:全局作用域的请求,可以设置为对象数组对象
  • modules:带命名空间的请求,类型为对象,属性名即为命名空间

loadingProp

挂载到 Vue.prototype 上的属性名,默认是 $loading

github地址

转载于:https://juejin.im/post/5cfb5fbd51882506400069ae

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值