怎么在vue项目中自动设置请求状态?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
async handler() {
this.loading = true
await fetch()
this.loading = false
}
虽然是很简单的功能,可是要处理的地方多的时候,还是很繁琐的,就想着能不能统一设置处理请求的 loading ,然后页面根据 loading 的状态决定要显示的内容,就根据自己的想法做了一些封装,自动给所有 ajax 请求设置 loading 状态,主要思路是把所有请求集中到单一实例上,通过 proxy 代理属性访问,把 loading 状态提交到 store 的 state 中
安装
$ 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.loading
或 this.$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
包含所有请求的对象,可以配置 global 和 modules 属性
global:全局作用域的请求,可以设置为 对象 或 数组对象
modules:带命名空间的请求,类型为 对象 ,属性名即为命名空间
Vue是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。