Vue.js-Axios

Axios

JS面向对象

ES5的构造对象的方式 使用构造函数来创造。构造函数唯一的不同是函数名首字母要大写。

function Point(x, y){
    this.x = x;
    this.y = y;
}

// 给父级绑定方法
Point.prototype.toSting = function(){
    return '(' + this.x + ',' + this.y + ')';
}

var p = new Point(10, 20);
console.log(p.x)
p.toSting();

ES6 使用Class构造对象的方式:

class Point{
    constructor(x, y){
        this.x = x;
        this.y = y;
    }  // 不要加逗号
    toSting(){
        return `(${this.x}, ${this.y})`;
    }
}

var p = new Point(10, 20);
console.log(p.x)
p.toSting();

Promise

Promise 是异步编程的一种解决方案,比传统的解决方案(回调函数和事件)更合理、更强大。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。

使用Promise的优势是有了Promise对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise对象提供统一的接口,使得控制异步操作更加容易。

$.ajax({
    url:'/books/',
    type: 'get',
    success: function(res){
        // 请求成功之后要做的事儿
        // 又要发ajax请求去请求数据
        $.ajax({
            url: '/author/?id=1',
            type: 'get',
            success: function(res){
                // 回调函数一直往右写
            }
        })
    }
})

promise写法

promise对象多用于表示一个异步操作,

.then():当异步操作成功之后会做的事儿

.catch(error):当异步操作出错的时候会做的事儿

$.ajax({
    url: '/books/',
    type: 'get'
})
.then(function(){
    
})
.catch(function(error){
    
})
var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

console.log(promise1);
// expected output: [object Promise]

Axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

axios中文文档

// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

默认配置

Axios.defaults.baseURL = 'url';
// 自动拼接请求地址
posted @ 2019-08-16 16:07  写bug的日子  阅读(195)  评论(0编辑  收藏  举报