VUE2中axios的使用方法
一,安装
npm install axios
二,在http.js中引入
import axios from 'axios';
三,定义http request 拦截器,添加数据请求公用信息
1 axios.interceptors.request.use( 2 config => { 3 // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie 4 //config.data = JSON.stringify(config.data); 5 let token = localStorage.token; 6 //let token = 'xxx'; 7 let appid = 'xxx'; 8 let appID = decodeURIComponent(appid); 9 config.headers.token = token; 10 //config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; 11 12 if (config.method == 'get') { 13 config.params.app_id = appID 14 config.params.token = token 15 } 16 if (config.method == 'post') { 17 config.data.token = token 18 config.data.app_id = appID 19 } 20 21 return config; 22 }, 23 error => { 24 return Promise.reject(err); 25 } 26 );
四,封装get方法
export function get(url, params = {}) { return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data); }) .catch(err => { reject(err) }) }) }
五,封装post方法
export function post(url, params = {}) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
六,封装patch请求
export function patch(url, data = {}) { return new Promise((resolve, reject) => { axios.patch(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
七,封装put请求
export function put(url, data = {}) { return new Promise((resolve, reject) => { axios.put(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
八,实现跨域
1 const downloadUrl = url => { 2 let iframe = document.createElement('iframe') 3 iframe.style.display = 'none' 4 iframe.src = url 5 iframe.onload = function() { 6 document.body.removeChild(iframe) 7 } 8 document.body.appendChild(iframe) 9 }
九,方法的使用
在main.js里引入http.js
1 import Vue from 'vue' 2 import App from './App' 3 import router from './router' 4 import axios from 'axios' 5 import {get, post } from '@/utils/http' 6 7 Vue.prototype.$ajax = axios; 8 Vue.prototype.$post = post; 9 Vue.prototype.$get = get;
在需要调用的地方
this.$get(url).then((response) => { } })
this.$post(url, data).then((response) => { } })
this.$put(url, data).then((response) => { } })
this.$patch(url, data).then((response) => { } })