我是靠谱客的博主 细腻羽毛,这篇文章主要介绍封装Vue的请求实现接口快速方便接通,现在分享给大家,希望可以做个参考。

一、index.html里写入接口公共部分

复制代码
1
2
3
4
<script> window.url='http://192.168.1.1:8080/' </script>

二、新建tool.js文件封装ajax请求,src/until/tool.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
const Tool = {}; /** * 发送ajax请求和服务器交互 * @param {object} mySetting 配置ajax的配置 */ Tool.ajax = function (mySetting) { var setting = { url: window.location.pathname, //默认ajax请求地址 async: true, //true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false type: 'GET', //请求的方式 data: {}, //发给服务器的数据 dataType: 'json', view:null, title:null, success: function (view) { }, //请求成功执行方法 error: function (view) { } //请求失败执行方法 }; var aData = []; //存储数据 var sData = ''; //拼接数据 //属性覆盖 for (var attr in mySetting) { setting[attr] = mySetting[attr]; } setting.type = setting.type.toUpperCase(); var xhr = new XMLHttpRequest(); try { if (setting.type == 'GET') { //get方式请求 for (var attr in setting.data) { aData.push(attr + '=' + filter(setting.data[attr])); } sData = aData.join('&'); sData = setting.url + '?' + sData; xhr.open(setting.type, sData + '&' + new Date().getTime(), setting.async); xhr.send(); } else if(setting.type=='POST'){ //post方式请求 if(setting.dataType=='img'){ console.log('上传图片'); var formData = new FormData(); formData.append('123', null); xhr.open(setting.type, setting.url, setting.async); xhr.setRequestHeader("Content-type", "multipart/form-data"); xhr.send(formData); }else{ for (var attr in setting.data) { aData.push(attr + '=' + filter(setting.data[attr])); } sData = aData.join('&'); xhr.open(setting.type, setting.url, setting.async); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(sData); } } } catch (e) { return httpEnd(); } if (setting.async) { xhr.addEventListener('readystatechange', httpEnd, false); } else { httpEnd(); } function httpEnd() { if (xhr.readyState == 4) { var head = xhr.getAllResponseHeaders(); var response = xhr.responseText; //将服务器返回的数据,转换成json if (/application/json/.test(head) || setting.dataType === 'json' && /^({|[)([sS])*?(]|})$/.test(response)) { response = JSON.parse(response); } if (xhr.status == 200) { setting.success(response,setting.view, setting, xhr); } else { setting.error(setting.view,setting, xhr); } } } xhr.end = function () { xhr.removeEventListener('readystatechange', httpEnd, false); } function filter(str) { //特殊字符转义 str += ''; //隐式转换 str = str.replace(/%/g, '%25'); str = str.replace(/+/g, '%2B'); str = str.replace(/ /g, '%20'); str = str.replace(///g, '%2F'); str = str.replace(/?/g, '%3F'); str = str.replace(/&/g, '%26'); str = str.replace(/=/g, '%3D'); str = str.replace(/#/g, '%23'); return str; } return xhr; }; /** * 封装ajax post请求 * @param {string} pathname 服务器请求地址 * @param {object} data 发送给服务器的数据 * @param {function} success 请求成功执行方法 * @param {function} error 请求失败执行方法 */ Tool.post = function (pathname, data,view,success, error,title) { var setting = { url: pathname, //默认ajax请求地址 type: 'POST', //请求的方式 data: data, //发给服务器的数据 view:view, title:title, success: success || function () { }, //请求成功执行方法 error: error || function () {} //请求失败执行方法 }; return Tool.ajax(setting); }; /** * 封装ajax get请求 * @param {string} pathname 服务器请求地址 * @param {object} data 发送给服务器的数据 * @param {function} success 请求成功执行方法 * @param {function} error 请求失败执行方法 */ Tool.get = function (pathname, data, success, error) { var setting = { url: pathname, //默认ajax请求地址 type: 'GET', //请求的方式 data: data, //发给服务器的数据 success: success || function () { }, //请求成功执行方法 error: error || function () { } //请求失败执行方法 }; return Tool.ajax(setting); }; Tool.upImg = function (pathname, data,view, success, error) { var setting = { url: pathname, //默认ajax请求地址 type: 'POST', //请求的方式 dataType:'img', data: data, //发给服务器的数据 view:view, success: success || function () { }, //请求成功执行方法 error: error || function () { } //请求失败执行方法 }; return Tool.ajax(setting); };

三、新建base.js,src/interface/base.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Toast } from 'vant'; const Base= {}; Base.key='test'; Base.log=function(data,title){ console.log('--------------------'+title+'--------------------'); let msg=JSON.stringify(data); console.log('data:'+msg); console.log('--------------------'+title+'--------------------'); } const request={} request.log=function(data,url,title){ console.log('--------------------'+title+'--------------------'); console.log('url:'+url); console.log(data); console.log('--------------------'+title+'--------------------'); } request.init=function(data,view){ view.loading=true; Toast.loading({mask: false,message: '加载中...'}); } const success={} success.log=function(data,title){ console.log('--------------------'+title+'--------------------'); console.log("成功:") console.log(data); console.log('--------------------'+title+'--------------------'); } success.init=function(data,view){ view.loading=false; Toast.clear(); // Toast.success('加载成功'); } const error={} error.log=function(data,title){ console.log('--------------------'+title+'--------------------'); console.log("失败:") console.log('--------------------'+title+'--------------------'); } error.init=function(data,view){ // view.loading=false; Toast.fail('加载失败'); } function Error(res, view,title){ Base.success.log(res,title); Base.error.init(res,view); } Base.Error=Error; function Success(res, view,title){ Base.success.log(res,title); Base.success.init(res,view); } Base.Success=Success; //请求 Base.request=request; //响应失败 Base.error=error; //请求成功 Base.success=success; export default Base;

四、接口请求,interface/user.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//系统一些自带的 请求 import tool from '../util/tool'; import base from './base'; import { Toast } from 'vant'; const User = {} User.url = window.url; function error(view,res) { base.Error(res, view) } const register={}; register.title='注册'; register.url=User.url+'user/userRigiseter'; register.post=function(data,view){ let _this = this; base.request.init(data,view); base.request.log(data,_this.url,_this.title); return tool.post(_this.url,data,view,_this.success,error,_this.title); } register.success=function(res, view) { base.Success(res, view,this.title) if(res.code=='200'){ view.registerSuccess(res); }else{ view.registerError(res); } } User.register=register;

五、在Vue里调用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template> <div></div> </template> <script> import User from '@/interface/user'; import { Toast,Dialog } from 'vant';//vant组件库,可不用 import Tool from '@/util/tool'; export default { data() { return { passWord:'', phone:'', sms:'', } }, methods: { // 注册 register(res){ let para={ phoneNumber:this.phone, SmsCode:this.sms, userPassword:'' } User.register.post(para,this); }, // 注册成功 registerSuccess(res){ console.log('注册成功') }, //注册失败 registerError(){ console.log('注册失败') } }, } </script>

最后

以上就是细腻羽毛最近收集整理的关于封装Vue的请求实现接口快速方便接通的全部内容,更多相关封装Vue内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部