Vue3(管理系统)-封装axios(utils)

一、在utils下编写request.js实例

1.添加基地址,设置超时时间

import axios from 'axios'
const baseURL = 'http://big-event-vue-api-t.itheima.net'
const instance = axios.create({
  // TODO 1. 基础地址,超时时间
  baseURL,
  timeout: 3000
})

2.添加请求拦截器

import { useUserStore } from '@/store'
// 添加请求拦截器

axios.interceptors.request.use(
  function (config) {
    //     // config:
    // 在发送请求之前做些什么
    //携带token
    const userStore = useUserStore()
    if (userStore) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么

    return Promise.reject(error)
  }
)

3.添加响应拦截器

import { ElMessage } from 'element-plus'
//这里是element-plus的导入消息框

import router from '@/router'




//弹窗提示
const open4 = () => {
  ElMessage({
    message: 'response.data.message ' || '请求失败,请稍后再试',
    type: 'error',
    plain: true
  })
} 

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    if (response.data.code === 0) {
      return response
    }
    // 处理业务失败抛出错误常规
    open4()
    return Promise.reject(response.data)
  },
  function (error) {
    // 对响应错误做点什么
    // 默认错误
    ElMessage({
      message: error.response.data.message || '服务异常',
      type: 'error',
      plain: true
    })
    console.log(error)
    // 401错误,权限不足,token过期,跳转登录
    //?表示可选链
    if (error.response?.status === 401) {
      // 跳转登录
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
export default instance
export { baseURL }

最后导出

二、可选链(扩展)

可选链(Optional Chaining)是编程语言中的一种特性,它允许你访问对象的嵌套属性,即使这些属性可能未被初始化或不存在。在 JavaScript 或 TypeScript 中,可选链的语法使用问号 ?. 来表示。

以下是可选链的一些常见用法:

  1. 访问对象的嵌套属性

     

    const obj = { foo: { bar: { baz: 'Hello World' } } }; // 使用可选链 const baz = obj?.foo?.bar?.baz; // "Hello World" // 不使用可选链,如果任一属性不存在,将导致错误 const baz = obj.foo.bar.baz; // 如果 obj.foo 或 obj.foo.bar 不存在,将抛出错误

  2. 函数调用: 如果一个函数可能不存在,使用可选链可以避免错误:

     

    const obj = { doSomething: () => console.log('Doing something') }; // 使用可选链调用函数 obj?.doSomething?.(); // "Doing something" // 如果 doSomething 不存在,不会抛出错误

  3. 与解构结合使用

     

    const obj = { foo: { bar: 42 } }; // 使用可选链进行解构 const { foo: { bar } = 0 } = obj; // 使用可选链进行解构,避免错误 const { foo: { bar } = 0 } = someUnknownObject;

  4. 链式调用

     

    const obj = { foo: { bar: () => 'Hello World' } }; // 使用可选链进行链式调用 const result = obj?.foo?.bar?.(); // 如果 foo 或 bar 不存在,result 将是 undefined 而不是抛出错误

  5. 条件表达式

     

    const obj = { foo: { bar: 'baz' } }; // 使用可选链进行条件表达式 const value = obj?.foo?.bar || 'default'; // value 将是 'baz',如果 obj.foo 或 obj.foo.bar 不存在,将是 'default'

可选链是一个非常有用的特性,它可以减少代码中的条件检查,使代码更加简洁。然而,它也可能导致一些微妙的错误,因为可选链返回 undefined 而不是抛出错误,所以使用时需要仔细考虑逻辑。

三、

  • 15
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3和TypeScript封装axios可以按照以下步骤进行操作: 1. 首先,在项目的src目录下创建一个utils文件夹,并在其中创建一个request.ts文件。在该文件中,导入axios并创建一个axios实例。可以使用引用\[2\]中的代码作为参考,设置基地址和请求超时时间。 2. 在request.ts文件中,可以封装一个函数request,该函数接受url、method和可能有/可能无的接口请求参数作为参数。在函数内部,使用axios实例发送请求,并返回一个Promise对象。可以使用引用\[1\]中的代码作为参考,使用axios实例的伪代码。 3. 在src目录下的根目录中创建一个axios文件夹,并在其中创建一个index.ts文件。在该文件中,可以进行axios的配置,包括实例化请求配置、请求拦截器和响应拦截器等。可以使用引用\[3\]中的代码作为参考。 通过以上步骤,你可以在Vue3和TypeScript中成功封装axios,并使用封装后的axios发送请求。 #### 引用[.reference_title] - *1* *2* [TS+Axios封装vue3.x环境)](https://blog.csdn.net/u011690675/article/details/130160009)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Vue3 + Ts 封装axios](https://blog.csdn.net/qq_35624605/article/details/121074339)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值