vue中使用axios进行http通信

1.安装

npm install axios

2.在main.js中全局注册

// axios不可以通过use引入,可以通过修改vue原型链
import axios from 'axios'
Vue.prototype.$ajax = axios

3.在组件中使用(方法一)

// .then .catch拥有各自独立的作用域,在后面添加.bind(this)可以使this指向组件实例
this.$ajax.post('/dnalims/svc/loaddict', data).then(function(res) {
  console.log(res)
}.bind(this))

4.在组件中使用(方法二)

建立axios参数配置文件,axiosConfig.js

import Qs from 'qs'
export default {
    serviceConfig: {
        //请求的接口,在请求的时候,如axios.get(url,config);这里的url会覆盖config中的url
        url: '/',
        //请求方法同上
        method: 'POST',
        //基础url前缀
        baseURL: '/dnalims/svc/',
        withCredentials: true,
        //请求头信息
        headers: {
            // 'X-Requested-width': 'XMLHTTPRequest'
        },
        //post参数,使用axios.post(url,{},config);如果没有额外的也必须使用空对象,否则会报错
        data: {
            //默认空对象
        },
        //设置超时时间
        timeout: 30000,
        //返回数据类型
        responseType: 'json', //default
    }

}

封装axios方法,axiosHttp.js

import axios from 'axios'
import config from './axiosConfig'
// 封装axios方法
function govue(api, data, callback) {
    axios.post(api, data, config.serviceConfig).then(function (response) {
        //回调成功
        callback(response.data);
    }).catch(function (response) {
        //回调失败
        console.log(response);
    })
}
export {
    govue
}

在组件中使用

let api = 'loaddict'
let data = '{"dict_category":"RELATION_WITH_TARGET"}'
govue(api, data, function(res){
  console.log(res)
})

较为详细的axios讲解文章:http://www.cnblogs.com/yuqing6/p/6954114.html

原文地址:https://www.cnblogs.com/sangzs/p/8984398.html