vue axios 封裝 全局使用
阿新 • • 發佈:2018-08-08
== new pan exp vue then onf out code
【不墨跡直接上碼系列】
代碼分三步:
1. 創建一個api.js,封裝axios
2. 在main.js引入,並加到vue原型上
3. 全局使用
1. 創建+封裝
//api.js import axios from "axios"; var apiUrl = ‘‘; function yuanAjax(url,data,successCallback,errorCallback) { axios.post(apiUrl + url,data).then(function (res) { if( typeof successCallback == ‘function‘) { successCallback(res); } }) .catch(function (res) { if (errorCallback) { errorCallback(res); } }) } export { yuanAjax }
2.引入+添加到原型
import Vue from ‘vue‘ import App from ‘./App‘ import router from ‘./router‘ //引入 import {yuanAjax} from ‘./api‘ import ElementUI from ‘element-ui‘; import ‘element-ui/lib/theme-chalk/index.css‘; import‘@/assets/css/common.css‘; import ‘@/assets/css/font-awesome.min.css‘; Vue.use(ElementUI); Vue.config.productionTip = false; //添加到原型 Vue.prototype.yuanAjax = yuanAjax; new Vue({ el: ‘#app‘, router, components: { App }, template: ‘<App/>‘ })
3. 使用
//使用 this.yuanAjax(‘/test‘,{ a:1 },function(res) { console.log(res); })
簡單了點,適用著急的項目, 哈哈
vue axios 封裝 全局使用