每个项目网络请求接口封装都是很重要的一块,第一次做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//请求返回数据
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
继续阅读与本文标签相同的文章
-
滴滴与清华大学建未来出行联合研究中心
2026-05-18栏目: 教程
-
市场再出人性化软件!这还只是新起点?方便了这些群体
2026-05-18栏目: 教程
-
《Android高性能编程》| 每日读本书
2026-05-18栏目: 教程
-
上海市增值税发票管理系统25日停机前需完成以下事项
2026-05-18栏目: 教程
-
设计建设网站前,网站安全整体解决方案全解析!
2026-05-18栏目: 教程
