Vue.js - Study Note 7

Views: 1172
Wrote on April 15, 2020, 7:09 p.m.

Axios

Axios is a great http client library. It uses promises by default and runs on both the client and the server (which makes it appropriate for fetching data during server-side rendering). It’s also quite easy to use with Vue. Because it uses promises, you can combine it with async/await to get an amazingly concise and easy-to-use API, as I will demonstrate here.

Install Axios

$ npm install --save axios

Then add method in main.js so that Axios can be used globally.

import Vue from 'vue'
import App from './App'
import axios from 'axios'

Vue.prototype.$http = axios

app = new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

Basically, IE doesn’t support promise, so you may need polyfill of es6-promise to enable it. You can install it with command below.

$ npm install --save es6-promise

Next, just add one line below in your webpack config file.

require('es6-promise').polyfill();

Use

<div id="app">
  {{ info }}
</div>
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})
</script>

Why not AJAX

Handling Ajax request within a Vue application was previously made easy by using vue-resource, which has now been retired. This means any 3rd party libraries can be used for the purpose of making Ajax request, but as recommended by Yuxi You (Evan You), we will use Axios. Axios is a commendable promise-based HTTP client library that runs on both the client and the server.

Vue don't use jQuery for ajax because: - If $ is already available in the component, it's more tempting to query or manipulate the DOM instead of using v-model, v-if,:class, etc. - Axios is an excellent library for ajax and uses less kb than jQuery. - Could lead to a hard to maintain a mix between jQuery plugins and Vue components.

Summary

As Vue team suggested, there are many ways to work with Vue and axios beyond consuming and displaying an API. You can also communicate with Serverless Functions, post/edit/delete from an API where you have write access, and many other benefits. Due to the straightforward integration of these two libraries, it’s become a very common choice for developers who need to integrate HTTP clients into their workflow.