为什么使用axios

在vue中发送ajax有很多工具可供我们使用,比如浏览器自带的fetch函数,也可以使用vue以前推荐的resource这样的一个第三方模块。现在vue官方推荐我们使用axios这样的一个第三方模块。
axios:基于 promise 的 HTTP 客户端
axios的功能:在浏览器端axios可以帮助你发送xhr请求,在node服务器上可以发送http请求。

使用axios的步骤

1.安装axios npm install axios --save

2.引入axios

页面是由许多个组件组成,每个组件都有自己的json数据,如果每个组件都单独请求一个ajax,那么整个页面就会发送许多个ajax请求,这样的页面运行肯定是很慢的。

我们希望整个页面只请求一个json数据,也就是只发送一个ajax请求

对于这种情况,在整合了子组件的.vue文件中进行ajax请求。例如下面这种情况:

axios每次发送前都在url中添加参数 使用axios发送ajax请求_json


然后通过子父组件传值,把每个子组件需要的数据都传给子组件。

在.vue文件中,import axios from 'axios’引入axios

3.借助mounted生命周期函数来使用aioxs

mounted(){
  this.getHomeInfo()
  },

当页面挂载好(mounted)之后,完成getHomeInfo函数的调用,这个函数帮助我们完成ajax数据的获取
再在methods中使用这个函数

methods:{
  getHomeInfo(){
  axios.get('/api/index.json')
  //axios返回的是一个promise对象
    .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc(res){
    //定义数据获取成功之后的事情
    }

实现父子组件间传值:
1.在data中返回需要的数据,例如:

data () {
    return {
      city: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },

2.在getHomeInfoSucc函数中进行处理

getHomeInfoSucc: function (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.city = data.city
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },

vue.js官网上也有详细教程:
https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html 创建一个过滤器来确保小数部分的合理展示:

filters: {
  currencydecimal (value) {
    return value.toFixed(2)
  }
},

错误处理:
对于axios中出现的三种错误:
1.API 不工作了;
2.请求发错了;
3.API 没有按我们预期的格式返回信息

使用catch来检查这些情况:

axios
  .get('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(response => (this.info = response.data.bpi))
  .catch(error => console.log(error))

当数据长时间生成不出来或 API 不工作的时候,构造一个加载效果;在完全无法显示数据时,通知用户:

<div id="app">
  <h1>Bitcoin Price Index</h1>

  <section v-if="errored">
    <p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
  </section>

  <section v-else>
    <div v-if="loading">Loading...</div>

    <div
      v-else
      v-for="currency in info"
      class="currency"
    >
      {{ currency.description }}:
      <span class="lighten">
        <span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
      </span>
    </div>

  </section>
</div>
new Vue({
  el: '#app',
  data () {
    return {
      info: null,
      loading: true,
      errored: false
    }
  },
  filters: {
    currencydecimal (value) {
      return value.toFixed(2)
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data.bpi
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
  }
})

在没有后端的支持下,实现数据的模拟

1.在static文件下新建一个mock文件夹,在里面新建一个index.json文件

(在本地文件中,只有static目录下的文件可以在网页中访问到)

2.不希望把mock文件夹里的内容添加到线上,打开主目录下的.gitignore文件加上static/mock,mock文件夹就不会被提交到线上

3.webpack-dev-server为我们提供了一个代理props功能,可以帮助我们把api文件夹下的json文件转发到本地的mock文件夹下

axios每次发送前都在url中添加参数 使用axios发送ajax请求_ios_02


当我们请求api这个目录的时候,把请求转发到当前的8080端口上,然后把路径做一个替换pathRewrite,一旦请求的地址是以api开头的,就把它替换成’static/mock’这个路径下的文件。

修改配置后,需要重新启动一下项目 npm run dev/start