vue-cli中使用axios

Posted 五个唔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue-cli中使用axios相关的知识,希望对你有一定的参考价值。

安装

npm install axios --save-dev

使用方式

  • 引入包
import axios from ‘axios‘
  • axios不是vue的插件,不能使用Vue.use(). 要通过控制原型链的方式来引入。
Vue.prototype.$http = axios
  • 在项目中使用
          this.$http.get(‘https://erienniu.xyz/api/sidebar‘)
            .then(function(response) {
              console.log(response.data)
            })
            .catch(function(error) {
              console.log(error)
            })

跨域问题需要用jsonp时

https://github.com/axios/axios/blob/master/COOKBOOK.md#jsonp

$ npm install jsonp --save
const jsonp = require(‘jsonp‘);

jsonp(‘http://www.example.com/foo‘, null, (err, data) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});

以上是关于vue-cli中使用axios的主要内容,如果未能解决你的问题,请参考以下文章