Vue 学习随笔七 - Axios封装
Vue推荐最近很流行的Axios进行Http Ajax操作,由于需要跟后台交互,判断 restful 接口的返回,故,简单的对Axios进行一个封装,慢慢的会不住的完善,请看下面的目录结构:
api里面是对后台rest api的地址定义,http是对axios的封装,请参见JS
1 let host = 'http://127.0.0.1:8078/' 2 const Api = { 3 user: { 4 get: host + 'user/get', 5 add: host + 'user/add', 6 del: host + 'user/del', 7 page: host + 'user/page' 8 } 9 } 10 11 export default Api
1 // 返回状态code 0 网络错误 1 请求失败 2 成功 2 // TODO 封装 axios 3 export default { 4 name: 'HttpPlugin', 5 install: function(Vue, options) { 6 Vue.prototype.$httpAwait = async function(url, params) { 7 let res = await this.$axios.get(url, { params: params }) 8 let obj = res.data 9 if (obj.code == 2) return res.data.data 10 else alert(obj.message) 11 return false 12 } 13 14 Vue.prototype.$HttpGet = function(url, params, callback) { 15 this.$axios.get(url, { params: params }).then(response => { 16 let obj = response.data 17 if (obj.code == 2) callback(obj) 18 else alert(obj.message) 19 return false 20 }) 21 } 22 23 Vue.prototype.$HttpPost = function(url, params, callback) { 24 this.$axios.get(url, { params: params }).then(response => { 25 let obj = response.data 26 if (obj.code == 2) callback(obj) 27 else alert(obj.message) 28 return false 29 }) 30 } 31 } 32 }
使用方式请参见上文所述的add.js