vue3使用axios并封装axios请求的详细步骤
作者:suoh's Blog
Axios,是一个基于promise的网络请求库,作用于node.js和浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。
第一步:安装axios

npm install axios
第二步:编写请求文件
新建request.js

简单的axios封装,里面相关提示信息,自己可以引入element-plus去添加
/**axios封装
* 请求拦截、相应拦截、错误统一处理
*/
import axios from 'axios';
import QS from 'qs';
import router from '../router/index'
//qs.stringify()是将对象 序列化成URL的形式,以&进行拼接
// let protocol = window.location.protocol; //协议
// let host = window.location.host; //主机
// axios.defaults.baseURL = protocol + "//" + host;
axios.defaults.baseURL = '/api'
axios.interceptors.request.use( //响应拦截
async config => {
// 每次发送请求之前判断vuex中是否存在token
// 如果存在,则统一在http请求的header都加上token,这样后台根据token判断你的登录情况
// 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断
config.headers.token = sessionStorage.getItem('token')
return config;
},
error => {
return Promise.error(error);
})
// 响应拦截器
axios.interceptors.response.use(
response => {
if (response.status === 200) {
return Promise.resolve(response); //进行中
} else {
return Promise.reject(response); //失败
}
},
// 服务器状态码不是200的情况
error => {
if (error.response.status) {
switch (error.response.status) {
// 401: 未登录
// 未登录则跳转登录页面,并携带当前页面的路径
// 在登录成功后返回当前页面,这一步需要在登录页操作。
case 401:
break
// 403 token过期
// 登录过期对用户进行提示
// 清除本地token和清空vuex中token对象
// 跳转登录页面
case 403:
sessionStorage.clear()
router.push('/login')
break
// 404请求不存在
case 404:
break;
// 其他错误,直接抛出错误提示
default:
}
return Promise.reject(error.response);
}
}
);
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
const $get = (url, params) => {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params,
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
const $post = (url, params) => {
return new Promise((resolve, reject) => {
axios.post(url, QS.stringify(params)) //是将对象 序列化成URL的形式,以&进行拼接
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
//下面是将get和post方法挂载到vue原型上供全局使用、
// vue2.x中是通 Vue.prototype 来绑定的,像这样Vue.prototype.$toast = Toast。在vue3中取消了Vue.prototype,推荐使用globalProperties来绑定,
export default {
install: (app) => {
app.config.globalProperties['$get'] = $get;
app.config.globalProperties['$post'] = $post;
app.config.globalProperties['$axios'] = axios;
}
}几个需要注意的点:
1、我们可以通过window.location.protocol和window.location.host获取协议和主机ip端口,然后统一设置axios的默认请求baseURL
// let protocol = window.location.protocol; //协议 // let host = window.location.host; //主机 // axios.defaults.baseURL = protocol + "//" + host;
2、qs.stringify()是将对象 序列化成URL的形式,以&进行拼接
(1)先引入 qs模块
import QS from 'qs';
(2)在请求参数前面包裹使用

(3)查看参数结果,就转换为了formdata传参形式,方便快捷、

3、全局挂载,vue2.x中是通 Vue.prototype 来绑定的,例如 Vue.prototype.$toast = Toast。在vue3中取消了Vue.prototype,推荐使用 globalProperties 来绑定,挂载到组件的proxy上
export default {
install: (app) => {
app.config.globalProperties['$get'] = $get;
app.config.globalProperties['$post'] = $post;
app.config.globalProperties['$axios'] = axios;
}
}第三步:在main.js引入
注意:axios在request.js中已经全局引入了,在main.js中就不需要再引入axios,否则会报错

第四步:在组件中使用
引入

由于 Vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefined。因此我们需要通过getCurrentInstance 方法获取当前组件实例。
注意:getCurrentInstance只能在setup或生命周期钩子中使用。
proxy是getCurrentInstance()对象中的一个属性,然后通过对象的解构赋值方式拿到proxy。
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance();然后通过proxy拿到挂载好的get和post请求。
function testFunc() {
let data = {
roleId: "A",
username: "dpc",
password: "--",
sysType: "zhfw",
}
proxy.$post("/index/login", data).then((response) => {
console.log(response)
})
}到此这篇关于vue3使用axios并封装axios请求的文章就介绍到这了,更多相关vue3封装axios请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
