vue项目中axios请求网络接口封装的示例代码
更新时间:2018年12月18日 08:23:42 作者:honey缘木鱼
这篇文章主要介绍了vue项目中axios请求网络接口封装的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
每个项目网络请求接口封装都是很重要的一块,第一次做Vue项目,我们的封装方法如下:
(1).新建一个js文件,取名api.js
(2).引入 axios ,mint-UI ,如下图:
import axios from 'axios'
import {MessageBox, Toast} from 'mint-ui'
axios.defaults.timeout = 50000//默认请求超时时间
axios.defaults.headers = '请求头'
(2).封装get方法
export function getHttp (url, params = {}) {
// 创建动画mint-ui
Indicator.open({
text: '加载中...',
spinnerType: 'fading-circle'
})
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then(response => {
resolve(response.data)
Indicator.close() // // 关闭动画
})
.catch(err => {
reject(err)
Indicator.close() // // 关闭动画
MessageBox.alert('message', err)
})
})
}
(4).封装post方法
export function postHttp (url, data = {}) {
Indicator.open({
text: '加载中...',
spinnerType: 'fading-circle'
})
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
if (response.data.status == 1) {
resolve(response.data)
} else {
Toast(response.data.msg)
}
Indicator.close() // // 关闭动画
}, (err) => {
reject(err)
Indicator.close()
})
})
}
(5).封装后方法的使用
在main.js中引入全局变量
import {getHttp, postHttp} from './config/api'
Vue.prototype.$getHttp = getHttp
Vue.prototype.$postHttp = postHttp
//get网络请求
this.$getHttp(this.$shopUrl + 'api/product/list',)
.then((response) => {
response.result//请求返回数据
})
// post网络请求
this.$postHttp(this.$shopUrl + 'api/product/list',)
.then((response) => {
response.result//请求返回数据
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
VUE中computed 、created 、mounted的先后顺序说明
这篇文章主要介绍了VUE中computed 、created 、mounted的先后顺序说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-03-03
vue router总结 $router和$route及router与 router与route区别
这篇文章主要介绍了vue router总结 $router和$route及router与 router与route区别,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下2019-07-07
优化Vue template中大量条件选择v-if的方案分享
本文我们将给大家详细的讲解一下如何优化Vue template 中的大量条件选择v-if,文中通过代码示例介绍的非常详细,有详细的优化方案,感兴趣的朋友可以参考阅读下2023-07-07


最新评论