目前的几个项目里面有两种方式,一种是在plugins的axios的fetch.js里面将axios封装get和post然后在axios下的index.js里面import fetch 使用Plugin.install 来封装插件,在里面挂上VUE Vue.use(Plugin)
最后export default Plugin 再在plugins里面的index.js里面import axios/index ,再在main.js引入Plugin (import ‘@/plugins
/index.js’)注册到vue的$
属性上面(这个代码写到axios的index.js里面),变成全局的进行调用,this.$
或者vue.$或者window.来调。
这个层次有点多,主要是为了拆散代码,别的没啥用,就为了显示专业
还有就是在plugins里面将axios封装get和post然后,在用的时候从js文件里面import你封装的post或者get来使用。
我忍不住的吐槽一句,我这里的后端跑来改前端的axios,还给改乱了,我该如何找bug呢,你能不能不要在开发赶进度的时候这么干呀,优化可以后期随便整的呀
src下的
plugins 下的 fetch.js
import axios from ‘axios’
export default function fetch ({url, type, timeout, headers}){
return axios ({
method: type || ‘post’,
ur: ‘/pop/’+ url,
headers: headers || {'Content-Type': 'application/x-www-form-urlencoded'}
).then(res =>{
return res.data
}).catch(err => {
throw err
)}
}
plugin 的index.js
import ‘./fetch’
main.js
这里进行上vue
也可以直接在plugins的fetch里面注册
import ‘@/plugins/index’
import Vue from ‘vue’
Vue.prototype.$fetch = fetch
window.$fetch = fetch
使用时就
Vue.$fetch({
url: 'case/detail',
type: 'post'
params: {
ID: '837290',
UserName: 'xuemp'
},
// 头部设置参数,关于请求的格式一种是form一种是json,下面是json设置,默认是form,在axios封装时我们fetch里面用了与来设置的
header: { 'Content-Type': 'application/json'}
}) .then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
window.$fetch ({
url: 'case/detail',
type: 'get'
params: {
ID: '837290',
UserName: 'xuemp'
},
// 头部设置参数,关于请求的格式一种是form一种是json,下面是json设置,默认是form,在axios封装时我们fetch里面用了与来设置的
header: { 'Content-Type': 'application/json'}
}) .then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})