vue3怎么解决axios请求封装问题

其他教程   发布日期:2023年09月16日   浏览次数:458

这篇文章主要讲解了“vue3怎么解决axios请求封装问题”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue3怎么解决axios请求封装问题”吧!

vue3实战axios请求封装问题

1、在src目录下创建http文件夹,在http文件夹下分别创建index.js、request.js、api.js

2、index.js的作用:用于导出api.js定义的所有接口,代码如下

  1. export * from './api';

3、request.js代码如下:

  1. import axios from 'axios';
  2. import buildURL from 'axios/lib/helpers/buildURL';
  3. import { merge } from 'axios/lib/utils';
  4. //判断指定参数是否是一个纯粹的对象,所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的
  5. function isPlainObject (val) {
  6. return val && val.constructor.name === 'Object'
  7. }
  8. //请求之前进行拦截,可做的操作:1、添加loading的加载;2、添加请求头;3、判断表单提交还是json提交
  9. let requestInterceptors = [
  10. config => {
  11. //添加loading的加载
  12. //添加请求头
  13. config.headers.authorization = sessionStorage.getItem('Token');
  14. //判断表单提交还是json提交
  15. if (config.emulateJSON && isPlainObject(config.data)) {
  16. config.data = buildURL('', config.data).substr(1);
  17. }
  18. return config;
  19. }
  20. ]
  21. //请求响应之后进行拦截,可做操作:1、取消loading的加载;2、对返回状态进行判断:如请求错误、请求超时、获取数据失败、暂无数据等等
  22. let responseInterceptors = [
  23. res => {
  24. //取消loading加载
  25. //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等
  26. //返回结果
  27. return Promise.resolve(res);
  28. },
  29. err => {
  30. //取消loading加载
  31. //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等
  32. //返回结果
  33. return Promise.reject(err);
  34. }
  35. ]
  36. //组装请求
  37. let serviceCreate = config => {
  38. let service = axios.create(merge({}, config));
  39. service.interceptors.request.use(...requestInterceptors);
  40. service.interceptors.response.use(...responseInterceptors);
  41. return service
  42. }
  43. serviceCreate();
  44. export { serviceCreate, merge };

4、api.js代码如下:

  1. import { serviceCreate, merge } from '@/http/request';
  2. //这种方式可以采用单个项目的接口,也可以使用多个项目的接口,看自己的项目情况而定
  3. let http0 = serviceCreate({
  4. baseURL: '/project1/api1',
  5. timeout: 15000,//请求超时
  6. emulateJSON: true,//默认表单提交
  7. })
  8. let http1 = serviceCreate({
  9. baseURL: '/project2/api2',
  10. timeout: 15000,//请求超时
  11. emulateJSON: true,//默认表单提交
  12. })
  13. //get请求示例
  14. export function getData(params, config) {
  15. return http0.get('/project/list', merge(config, { params }));
  16. }
  17. //delete请求示例
  18. export function deleteData(params, config) {
  19. return http0.delete('/project/list', merge(config,{ params }));
  20. }
  21. //post请求示例(表单提交)
  22. export function postDataFrom(params, config) {
  23. return http0.post('/project/list', params, config);
  24. }
  25. //post请求示例(json提交)
  26. export function postDataJson(params, config) {
  27. return http0.post('/project/list', params, merge(config, { emulateJSON: false }));
  28. }
  29. //put请求示例(表单提交)
  30. export function putDataFrom(params, config) {
  31. return http0.put('/project/list', params, config);
  32. }
  33. //put请求示例(json提交)
  34. export function putDataJson(params, config) {
  35. return http0.put('/project/list', params, merge(config, { emulateJSON: false }));
  36. }

5、页面中调用

  1. import { getData, deleteData, postDataFrom, postDataJson, putDataFrom, putDataJson } from "@/http";
  2. getData({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
  3. deleteData({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
  4. postDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
  5. postDataJson({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
  6. putDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
  7. putDataJson ({ name: "我是参数" }).then(res => { console.log("返回数据", res) })

vue3 axios简易封装教程

首先在根目录下新建utils文件夹,并在下面新建两个文件,requests.js和html.js

requests.js用于引入axios并设置根域名以及一些默认设置、拦截器等。

  1. import axios from "axios";
  2. const service = axios.create({
  3. baseURL: 'http://localhost:3000',
  4. timeout: 10000,
  5. })
  6. // 请求拦截器
  7. service.interceptors.request.use(config=>{
  8. return config
  9. },err=>{
  10. return Promise.reject(err) //返回错误
  11. })
  12. // 响应拦截器
  13. service.interceptors.response.use(res=>{
  14. return res
  15. },err=>{
  16. return Promise.reject(err) //返回错误
  17. })
  18. export default service

写完之后将创建的实例对象暴露出去,在html.js中进行引入

html.js文件的作用是调用requests的实例对象,并将所有的访问均存放在这个文件中(api),使用的时候按需引入即可。

  1. import request from "./requests";
  2. export const GetPosts = () => request.get('posts/1')
  3. export const GetsearchData = (params) => request.get('/list',{params})
  4. export const PostPosts = (params) => request.post('posts',params)

引入的文件:

  1. <template>
  2. <el-button type="primary" @click="clickGet">点我发送get请求</el-button>
  3. <el-button type="primary" @click="clickPost">点我发送post请求</el-button>
  4. <el-button type="primary" @click="clickPut">点我发送put请求</el-button>
  5. <el-button type="primary" @click="clickDel">点我发送delete请求</el-button>
  6. </template>
  7. <script>
  8. import { GetPosts, PostPosts } from "../../utils/html"
  9. export default {
  10. setup(){
  11. function clickGet(){
  12. GetPosts().then(res => {
  13. console.log(res)
  14. })
  15. // axios({
  16. // method: 'GET',
  17. // url: 'http://localhost:3000/posts'
  18. // }).then(res => {
  19. // console.log(res)
  20. // })
  21. }
  22. function clickPost(){
  23. PostPosts({
  24. title: '我超级喜欢打游戏',
  25. author: '账本儿erer',
  26. age: '24'
  27. }).then(res => {
  28. console.log(res)
  29. })
  30. }
  31. function clickPut(){
  32. }
  33. function clickDel(){
  34. }
  35. return {
  36. clickDel,
  37. clickGet,
  38. clickPost,
  39. clickPut
  40. }
  41. }
  42. }
  43. </script>
  44. <style>
  45. </style>

以上就是vue3怎么解决axios请求封装问题的详细内容,更多关于vue3怎么解决axios请求封装问题的资料请关注九品源码其它相关文章!