VUE中axios的使用 封装方法

目前的几个项目里面有两种方式,一种是在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)
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值