• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

vue项目中axios请求网络接口封装的示例代码

vue 搞代码 4年前 (2022-01-08) 17次浏览 已收录 0个评论

这篇文章主要介绍了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 =<mark>本文来源gaodaimacom搞#^代%!码&网(</mark>> { 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//请求返回数据 }) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是vue项目中axios请求网络接口封装的示例代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:vue项目中axios请求网络接口封装的示例代码

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址