封装axios

使用promise 封装 ajax

// axios.get().then()

// hxios.get('url地址').then()

 

let hxios = {

get(url) {

// 返回promise对象

return new Promise((resolve, reject) => {

// ajax

let xhr = new XMLHttpRequest();

// 设置请求方法 和地址

xhr.open('get', url);

// 注册回调函数

xhr.onload = function () {

// promise resolve

resolve(xhr.responseText);

}

// 错误回调函数

xhr.onerror = function () {

// 调用reject

reject('请求出错啦')

}

// 发送ajax请求

xhr.send();

})

}

}

 

 

hxios.get('http://wthrcdn.etouch.cn/weather_mini?city=深圳')

.then(res => {

console.log(res);

// 查完了深圳 查北京 返回promise对象

return hxios.get('http://wthrcdn.etouch.cn/weather_mini?city=北京')

}).then(res => {

console.log(res);

// 再次返回promise对象

return hxios.get('http://wthrcdn.etouch.cn/weather_mini?city=武汉')

}).then(res => {

console.log(res);

})

 

 

如果回调函数很多的情况下就可以使用async和await

async created() {

// 依次往下执行

let res = await this.$axios.get("roles");

// console.log(res);

this.rolesList = res.data.data;

}

你可能感兴趣的:(封装,vue)