在vue中使用axios

本人也是做了很多vue的项目了,好像还没有正式写axios在vue中的用法,那么今天就来总结一下

1.在vue中引入axios

首先你先下载好依赖,然后就可以加入一下代码了

import Vue from 'vue'
import axios from 'axios';
import Qs from 'qs';//把默认axios  json格式传参形式变成key value的形式
Vue.prototype.$Qs = Qs;//this.$Qs.stringify(params);
Vue.prototype.$cookie = VueCookie;

引进来之后就可以在vue中使用this.$http.get(),this.$http.post()等函数
axios的官方文档地址在下方

https://www.kancloud.cn/yunye/axios/234845

首先我们来看一下它的一般用法

get请求

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

重点来了----拿小本本记好–本人还有更好的写法–看下去保证不会后悔

大家都知道ES7的 async await 吧,这么好的东西不能拿来为我所用简直太可惜了,本身axios就是基于promise封装出来的,正好贴合了这个 async await ,所以,我们完全不用写什么 then 函数
我直接上代码吧,不卖关子了

async getNewsList(){
            let last = await this.$http.get('/static/json/资讯动态-列表页.json');
            if(last.data.success){
                console.log(last.data)
                this.newsList = last.data.result;
                this.total = last.data.total;
                this.newsList.forEach((value,index) =>{
                    if(value.abstract.length > 116){
                        value.abstract = value.abstract.slice(0,117) + '...';
                    }
                })
            }else{
                this.newsList = [];
            }
        },

怎么样?是不是简直跟写同步代码一样?还不用写回调,哈哈!需要注意的是,async await必须结合使用,把async写到函数前面,await就写到你的ajax请求的地方,如果不写await就会报错,然后用一个变量,我这里是last接住,就可以处理你的逻辑了,是不是很神奇?
如果你用的vue-cli搭建的项目,同时配置了 babel-polyfill,那么你就大胆用这个 async await吧,妥妥的支持,如果不懂这个怎么用,我有一篇博客是专门介绍这个的,转过去就可以

使用ES6新特性async await进行异步处理

三哥微信公众号,打开你的微信,扫描它,然后带走我!

三哥QQ交流群

你可能感兴趣的:(vue.js)