vue2入门——axios用法

最近用vue2写完几个项目,这里从头回顾下Vue整个技术栈

axios的简单用法

我觉得只要是以前使用过JQ的ajax基本上对下面的几种用法不会陌生

  • get请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    axios.get('/detail',{
    params:{
    name:"zone"
    }
    }).then(function (res) {
    //成功获取数据
    console.log(res);
    }).catch(function (err) {
    //请求错误
    console.log(err);
    });

    这里的then 和catch 和明显是ES6 promise的用法 也就是axios是基于promise的HTTP库,自然兼容性也就最多到IE9.这一点很关键,不废话下面看post请求

  • post请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    axios.post('/add', {
    name: 'zone',
    age: 23
    }).then(function (res) {
    //请求成功
    console.log(res);
    }).catch(function (err) {
    //请求失败
    console.log(err);
    });

这里注意的是。当axios发送post请求的时候,参数直接和JQ的写法一致就行。

  • 多个请求并发的情况。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    function getProfile(){
    //请求1
    return axios.get('/profile');
    }
    function getUser(){
    //请求2
    return axios.get('/user');
    }

    //并发请求
    axios.all([
    getProfile(),
    getUser()
    ]).then(axios.spread((res1, res2)=>{
    //两个请求现已完成
    console.log(res1);
    console.log(res2);
    }));

我们事先定义了两个方法 getProfile()getUser() 帮我们实现get请求。

有时候会遇到要同时发送两个请求,当这两个请求都请求完毕返回的时候才能做下一步的逻辑判断。这时候就可以使用这个api。其实spread的中文名字就是传播。暗示传播到下一步的方法了?我也不是很明白 不过记住这个api就好了 哈哈

最后说几句

其实我还是觉得VUE挺好入门的。下次有机会总结下 Vue平时项目遇到的一些问题.自己积累也有一阵时间了