vue实践---vue结合 promise 封装原生ajax
有时候不想使用axios这样的外部依赖,想自己封装ajax,这里有两种方法
方法一,在单个页面内使用
封装的代码如下:
- beforeCreate () {
- this.$http = (() => {
- let createFetch = (type, url, params) => {
- return new Promise((resolve, reject) => {
- let xhr = new XMLHttpRequest()
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4){
- if(xhr.status === 200){
- var res = xhr.responseText;
- try {
- res = JSON.parse(xhr.responseText)
- } catch (e) {}
- resolve(res)
- } else {
- reject(xhr.responseText)
- }
- }
- }
- url += url.includes('?') ? '&' : '?'
- if (type === 'GET') {
- let serialArr = []
- Object.keys(params).forEach(v => {
- serialArr.push(`${v}=${params[v]}`)
- })
- url += serialArr.join('&')
- }
- xhr.withCredentials = true; //支持跨域发送cookies
- xhr.open(type, url, true);
- xhr.send(type === 'GET' ? null : params);
- })
- }
- return {
- get: (...args) => createFetch("GET", args[0], args[1]),
- post: (...args) => createFetch("POST", args[0], args[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)=>{
- if(res.flag == 0){
- this.requestData = res.data
- }
- })
方法二,全局注册
封装的方法如下:
- export default
- {
- install(Vue)
- {
- Vue.prototype.$http=function(options){
- /*将数据转化为字符串*/
- var strData=function(data){
- var dataStr="";
- for(var key in data){
- dataStr += key+'='+data[key]+'&';
- }
- dataStr = dataStr && dataStr.slice(0,-1);
- return dataStr;
- };
- /*创建 XMLHttpRequest 对象*/
- var createXHR=function(){
- var xhr;
- if (window.XMLHttpRequest)
- {// code for IE7+, Firefox, Chrome, Opera, Safari
- xhr=new XMLHttpRequest();
- }
- else {// code for IE6, IE5
- xhr=new ActiveXObject("Microsoft.XMLHTTP");
- }
- return xhr
- };
- /*向服务器发送请求*/
- var open=function(xhr,type,url,async){
- xhr.open(type,url,async);
- };
- var send=function(xhr,msg){
- xhr.send(msg);
- };
- var setHeaders=function(xhr,headers){
- xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
- if(!headers){
- return false;
- }
- for(var key in headers){
- xhr.setRequestHeader(key,headers[key]);
- }
- }
- var request=function(xhr,opts){
- if(opts.type==="GET"){
- open(xhr,opts.type,opts.url+'?'+strData(opts.data),opts.async);
- send(xhr,null);
- }
- else if(opts.type==="POST"){
- open(xhr,opts.type,opts.url,opts.async);
- if(opts.headers){
- setHeaders(xhr,opts.headers);
- }
- send(xhr,strData(opts.data));
- }
- };
- return new Promise((resolve,reject)=>{
- if(!options || typeof options != 'object'){
- reject(new Error("参数错误,请传入对象参数!"));
- return false;
- }
- if(!options.url){
- reject(new Error("url不能为空"));
- return false;
- }
- options.type = options.type?options.type.toUpperCase():'GET';
- options.async = (options.async && options.async === false)?false:true;
- options.dataType = options.dataType || "json";
- options.data = options.data || {};
- options.headers = options.headers || {};
- var dataStr=strData(options.data);
- /*创建 XMLHttpRequest 对象*/
- var xhr=createXHR();
- /*创建服务器返回响应后执行操作函数*/
- xhr.onreadystatechange=function(){
- var responseData;
- if(xhr.readyState == 4){
- switch (xhr.status){
- case 200:
- switch (options.dataType){
- case "xml":
- responseData=xhr.responseXML;
- break;
- case "text":
- responseData = xhr.responseText;
- break;
- case "json":
- responseData = JSON.parse(xhr.responseText);
- break;
- }
- resolve(responseData);
- default:
- reject(new Error("这里做错误处理"));
- }
- }
- };
- /*向服务器发送请求*/
- request(xhr,options);
- })
- };
- Vue.prototype.$post=function(options){
- options.type='post';
- return this.$http(options);
- };
- Vue.prototype.$get=function(options){
- options.type='get';
- return this.$http(options);
- };
- }
- }
- import Vue from 'vue'
- import App from './App.vue'
- import router from './router'
- import Install from './install/index.js'
// 这里全局安装- Vue.use(Install)
- new Vue({
- el: '#app',
- router,
- render: h => h(App)
- })
使用的代码如下:
- var reuestData = {
- url: "http://123.103.9.204:6058/official/rest/document/wenku/1/3293036/groupList",
- data: {pageSize: '1', pageSize: 30, groupType: 0}
- }
- this.$get(reuestData).then((res)=>{
- if(res.flag == 0) {
- this.requestData = res.data
- }
- })
两种方法的比较:
方法一的每个页面要想使用, 都需要写相关的代码,而且由于使用了匿名函数立即执行,如果函数内部有错误,不好调试
方法二使用了全局注册,只要在main.js 注册了全局都可以使用。
具体的代码可以看这里:https://github.com/YalongYan/vue-practice/tree/master/vue-native-ajax
vue实践系列请看这里:https://github.com/YalongYan/vue-practice
vue实践---vue结合 promise 封装原生ajax的更多相关文章
- 在vue项目中使用自己封装的ajax
在 src 目录下新建 vue.extend.js ,内容如下: export default { install(Vue) { Vue.prototype.$http=function(option ...
- vue实践---vue动态加载组件
开发中遇到要加载10个或者更多的,类型相同的组件时,如果用普通的 import 引入组件,components注册组件,代码显得太啰嗦了,这时候就需要用到 require.context 动态加载这些 ...
- vue实践---vue配合express实现请求数据mock
mock数据是前端比较常见的技术,这里介绍下vue配合express 实现请求数据mock. 第一步: 安装 express : npm install express -D 第二步: 简历需要mo ...
- vue实践---vue不依赖外部资源实现简单多语
vue使用多语,最常见的就是 vue-i18n, 但是如果开发中的多语很少,比如就不到10个多语,这样就没必要引入vue-i18n了, 引入了反正导致代码体积大了,这时候单纯用vue实现多语就是比较好 ...
- js 封装原生ajax
jquery框架的ajax方法固然好用,但是假如某天我们的项目不能引入jquery或项目需求很简单,没有很多交互功能,只需要ajax,这时引入jquery库会造成资源浪费,也会显得页面臃肿.这时我们就 ...
- 原生ajax解析&封装原生ajax函数
前沿:对于此篇随笔,完是简要写了几个重要的地方,具体实现细节完在提供的源码做了笔记 <一>ajax基本要点介绍--更好的介绍ajax 1. ajax对象中new XMLHttpReques ...
- 封装原生Ajax
var Chef = { createAjax:function() { var xhr = null; try { //IE系列浏览器 xhr = new ActiveXObject("m ...
- promise封装的ajax
var myNewAjax=function(url){ return new Promise(function(resolve,reject){ var xhr = new XMLHttpRequ ...
- ES6封装原生ajax请求
http (data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.onrea ...
随机推荐
- 关于MySQL Cluster集群NoOfReplicas参数问题
摘自:http://www.itpub.net/thread-1845295-1-1.html 官方网站上说参数NoOfReplicas的值表示数据的备份份数,例如:NoOfReplicas=2,若在 ...
- Android - toolbar navigation 样式
1.修改title 边距 修改边距使用系统的app属性来引入使用,即: xmlns:app="http://schemas.android.com/apk/res-auto" 1 ...
- 关于hibernate中映射中有many to one等外键关联时的问题
hibernate中的对象的3种状态的理解及导致报错object references an unsaved transient instance - save the transient insta ...
- [转载]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 ...
- input 中 datetime-local 方法
<input type=" datetime-local "> 这个标签是H5新增的对象方法 能把现有的时间赋值给它 但是注意:必须是 yyyy-MM-ddTHH: ...
- ECSHOP删除云服务
一.删除[云服务中心]删除/admin/cloud.php删除/admin/templates/menu.htm中以下代码 Ajax.call('cloud.php?is_ajax=1>act= ...
- 2017.7.18 linux下用户、组和文件的操作
参考来自:<鸟叔的linux私房菜(基础学习篇)-第14章> 0 目的 在linux下搭建ELK环境时,因为elasticsearch不能在root下操作,所以要为其新增一个用户,以及随之 ...
- HTML5 Canvas 动态勾画等速螺线
等速螺线亦称阿基米德螺线,得名于公元前三世纪希腊数学家阿基米德.阿基米德螺线是一个点匀速离开一个固定点的同时又以固定的角速度绕该固定点转动而产生的轨迹.在此向这位古代最伟大的数学家致敬.用Canvus ...
- node-表单验证
var http = require('http'); var url = require('url'); var fs = require('fs'); var querystring = requ ...
- 雷锋沙龙 ppt 演讲内容分享(xss,流量劫持的利用)
http://www.pkav.net/XSS.png?from=timeline&isappinstalled=0