有时候不想使用axios这样的外部依赖,想自己封装ajax,这里有两种方法

方法一,在单个页面内使用

封装的代码如下:

  1. beforeCreate () {
  2. this.$http = (() => {
  3. let createFetch = (type, url, params) => {
  4. return new Promise((resolve, reject) => {
  5. let xhr = new XMLHttpRequest()
  6. xhr.onreadystatechange = () => {
  7. if (xhr.readyState === 4){
  8. if(xhr.status === 200){
  9. var res = xhr.responseText;
  10. try {
  11. res = JSON.parse(xhr.responseText)
  12. } catch (e) {}
  13. resolve(res)
  14. } else {
  15. reject(xhr.responseText)
  16. }
  17. }
  18. }
  19. url += url.includes('?') ? '&' : '?'
  20.  
  21. if (type === 'GET') {
  22. let serialArr = []
  23. Object.keys(params).forEach(v => {
  24. serialArr.push(`${v}=${params[v]}`)
  25. })
  26. url += serialArr.join('&')
  27. }
  28. xhr.withCredentials = true; //支持跨域发送cookies
  29. xhr.open(type, url, true);
  30. xhr.send(type === 'GET' ? null : params);
  31. })
  32. }
  33. return {
  34. get: (...args) => createFetch("GET", args[0], args[1]),
  35. post: (...args) => createFetch("POST", args[0], args[1])
  36. }
  37. })()
  38. }

使用的代码如下:

  1. this.$http.get('http://123.103.9.204:6058/official/rest/document/wenku/1/3293036/groupList', {pageSize: '1', pageSize: 30, groupType: 0}).then((res)=>{
  2. if(res.flag == 0){
  3. this.requestData = res.data
  4. }
  5. })

方法二,全局注册

封装的方法如下:

  1. export default
  2. {
  3. install(Vue)
  4. {
  5. Vue.prototype.$http=function(options){
  6. /*将数据转化为字符串*/
  7. var strData=function(data){
  8. var dataStr="";
  9. for(var key in data){
  10. dataStr += key+'='+data[key]+'&';
  11. }
  12. dataStr = dataStr && dataStr.slice(0,-1);
  13. return dataStr;
  14. };
  15. /*创建 XMLHttpRequest 对象*/
  16. var createXHR=function(){
  17. var xhr;
  18. if (window.XMLHttpRequest)
  19. {// code for IE7+, Firefox, Chrome, Opera, Safari
  20. xhr=new XMLHttpRequest();
  21. }
  22. else {// code for IE6, IE5
  23. xhr=new ActiveXObject("Microsoft.XMLHTTP");
  24. }
  25. return xhr
  26. };
  27. /*向服务器发送请求*/
  28. var open=function(xhr,type,url,async){
  29. xhr.open(type,url,async);
  30. };
  31. var send=function(xhr,msg){
  32. xhr.send(msg);
  33. };
  34. var setHeaders=function(xhr,headers){
  35. xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  36. if(!headers){
  37. return false;
  38. }
  39. for(var key in headers){
  40. xhr.setRequestHeader(key,headers[key]);
  41. }
  42. }
  43. var request=function(xhr,opts){
  44. if(opts.type==="GET"){
  45. open(xhr,opts.type,opts.url+'?'+strData(opts.data),opts.async);
  46. send(xhr,null);
  47. }
  48. else if(opts.type==="POST"){
  49. open(xhr,opts.type,opts.url,opts.async);
  50. if(opts.headers){
  51. setHeaders(xhr,opts.headers);
  52. }
  53. send(xhr,strData(opts.data));
  54. }
  55. };
  56. return new Promise((resolve,reject)=>{
  57. if(!options || typeof options != 'object'){
  58. reject(new Error("参数错误,请传入对象参数!"));
  59. return false;
  60. }
  61. if(!options.url){
  62. reject(new Error("url不能为空"));
  63. return false;
  64. }
  65. options.type = options.type?options.type.toUpperCase():'GET';
  66. options.async = (options.async && options.async === false)?false:true;
  67. options.dataType = options.dataType || "json";
  68. options.data = options.data || {};
  69. options.headers = options.headers || {};
  70. var dataStr=strData(options.data);
  71. /*创建 XMLHttpRequest 对象*/
  72. var xhr=createXHR();
  73. /*创建服务器返回响应后执行操作函数*/
  74. xhr.onreadystatechange=function(){
  75. var responseData;
  76. if(xhr.readyState == 4){
  77. switch (xhr.status){
  78. case 200:
  79. switch (options.dataType){
  80. case "xml":
  81. responseData=xhr.responseXML;
  82. break;
  83. case "text":
  84. responseData = xhr.responseText;
  85. break;
  86. case "json":
  87. responseData = JSON.parse(xhr.responseText);
  88. break;
  89. }
  90. resolve(responseData);
  91. default:
  92. reject(new Error("这里做错误处理"));
  93. }
  94. }
  95. };
  96. /*向服务器发送请求*/
  97. request(xhr,options);
  98. })
  99. };
  100. Vue.prototype.$post=function(options){
  101. options.type='post';
  102. return this.$http(options);
  103. };
  104. Vue.prototype.$get=function(options){
  105. options.type='get';
  106. return this.$http(options);
  107. };
  108. }
  109. }
  1. import Vue from 'vue'
  2. import App from './App.vue'
  3. import router from './router'
  4.  
  5. import Install from './install/index.js'
    // 这里全局安装
  6. Vue.use(Install)
  7.  
  8. new Vue({
  9. el: '#app',
  10. router,
  11. render: h => h(App)
  12. })

使用的代码如下:

  1. var reuestData = {
  2. url: "http://123.103.9.204:6058/official/rest/document/wenku/1/3293036/groupList",
  3. data: {pageSize: '1', pageSize: 30, groupType: 0}
  4. }
  5. this.$get(reuestData).then((res)=>{
  6. if(res.flag == 0) {
  7. this.requestData = res.data
  8. }
  9. })

两种方法的比较:

方法一的每个页面要想使用, 都需要写相关的代码,而且由于使用了匿名函数立即执行,如果函数内部有错误,不好调试

方法二使用了全局注册,只要在main.js 注册了全局都可以使用。

具体的代码可以看这里:https://github.com/YalongYan/vue-practice/tree/master/vue-native-ajax

vue实践系列请看这里:https://github.com/YalongYan/vue-practice

vue实践---vue结合 promise 封装原生ajax的更多相关文章

  1. 在vue项目中使用自己封装的ajax

    在 src 目录下新建 vue.extend.js ,内容如下: export default { install(Vue) { Vue.prototype.$http=function(option ...

  2. vue实践---vue动态加载组件

    开发中遇到要加载10个或者更多的,类型相同的组件时,如果用普通的 import 引入组件,components注册组件,代码显得太啰嗦了,这时候就需要用到 require.context 动态加载这些 ...

  3. vue实践---vue配合express实现请求数据mock

    mock数据是前端比较常见的技术,这里介绍下vue配合express 实现请求数据mock. 第一步: 安装 express :  npm install express -D 第二步: 简历需要mo ...

  4. vue实践---vue不依赖外部资源实现简单多语

    vue使用多语,最常见的就是 vue-i18n, 但是如果开发中的多语很少,比如就不到10个多语,这样就没必要引入vue-i18n了, 引入了反正导致代码体积大了,这时候单纯用vue实现多语就是比较好 ...

  5. js 封装原生ajax

    jquery框架的ajax方法固然好用,但是假如某天我们的项目不能引入jquery或项目需求很简单,没有很多交互功能,只需要ajax,这时引入jquery库会造成资源浪费,也会显得页面臃肿.这时我们就 ...

  6. 原生ajax解析&封装原生ajax函数

    前沿:对于此篇随笔,完是简要写了几个重要的地方,具体实现细节完在提供的源码做了笔记 <一>ajax基本要点介绍--更好的介绍ajax 1. ajax对象中new XMLHttpReques ...

  7. 封装原生Ajax

    var Chef = { createAjax:function() { var xhr = null; try { //IE系列浏览器 xhr = new ActiveXObject("m ...

  8. promise封装的ajax

    var  myNewAjax=function(url){ return new Promise(function(resolve,reject){ var xhr = new XMLHttpRequ ...

  9. ES6封装原生ajax请求

    http (data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.onrea ...

随机推荐

  1. 关于MySQL Cluster集群NoOfReplicas参数问题

    摘自:http://www.itpub.net/thread-1845295-1-1.html 官方网站上说参数NoOfReplicas的值表示数据的备份份数,例如:NoOfReplicas=2,若在 ...

  2. Android - toolbar navigation 样式

    1.修改title 边距 修改边距使用系统的app属性来引入使用,即: xmlns:app="http://schemas.android.com/apk/res-auto" 1 ...

  3. 关于hibernate中映射中有many to one等外键关联时的问题

    hibernate中的对象的3种状态的理解及导致报错object references an unsaved transient instance - save the transient insta ...

  4. [转载]How to Install Google Chrome 39 in CentOS/RHEL 6 and Fedora 19/18

    FROM: http://tecadmin.net/install-google-chrome-in-centos-rhel-and-fedora/ Google Chrome is a freewa ...

  5. input 中 datetime-local 方法

    <input  type=" datetime-local "> 这个标签是H5新增的对象方法 能把现有的时间赋值给它 但是注意:必须是  yyyy-MM-ddTHH: ...

  6. ECSHOP删除云服务

    一.删除[云服务中心]删除/admin/cloud.php删除/admin/templates/menu.htm中以下代码 Ajax.call('cloud.php?is_ajax=1>act= ...

  7. 2017.7.18 linux下用户、组和文件的操作

    参考来自:<鸟叔的linux私房菜(基础学习篇)-第14章> 0 目的 在linux下搭建ELK环境时,因为elasticsearch不能在root下操作,所以要为其新增一个用户,以及随之 ...

  8. HTML5 Canvas 动态勾画等速螺线

    等速螺线亦称阿基米德螺线,得名于公元前三世纪希腊数学家阿基米德.阿基米德螺线是一个点匀速离开一个固定点的同时又以固定的角速度绕该固定点转动而产生的轨迹.在此向这位古代最伟大的数学家致敬.用Canvus ...

  9. node-表单验证

    var http = require('http'); var url = require('url'); var fs = require('fs'); var querystring = requ ...

  10. 雷锋沙龙 ppt 演讲内容分享(xss,流量劫持的利用)

    http://www.pkav.net/XSS.png?from=timeline&isappinstalled=0