小王同学
小王同学
发布于 2024-07-29 / 105 阅读
0

uniapp+ts

网络请求的封装

/*
 * @Author       : 2454988619@qq.com
 * @Date         : 2024-07-26 20:44
 * @LastEditors  : 2454988619@qq.com
 * @LastEditTime : 2024-07-29 20:20
 * @FilePath     : \heima-shop\src\utils\http.ts
 * @Description  : http请求封装
 */
// 请求基地址
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

import { useMemberStore } from '@/stores'

const httpInstance = {
  invoke(config: UniApp.RequestOptions) {
    if (!config.url.startsWith('http')) {
      config.url = baseURL + config.url
    }
    config.timeout = 10000
    config.header = {
      ...config.header,
      'source-client': 'miniapp',
    }
    const member = useMemberStore()
    const token = member.profile?.token
    if (token) {
      config.header.Authorization = token
    }
  },
}

uni.addInterceptor('request', httpInstance)
uni.addInterceptor('uploadFile', httpInstance)

interface Data<T> {
  code: string
  msg: string
  result: T
}

export const http = <T>(config: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...config,
      // 响应成功
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          const member = useMemberStore()
          member.clearProfile()
          uni.navigateTo({
            url: '/pages/login/login',
          })
          reject(res)
        } else {
          // 业务错误
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求失败',
            icon: 'none',
          })
          reject(res)
        }
      },
      // 响应失败 通用错误处理
      fail(err) {
        uni.showToast({
          title: '网络错误',
          icon: 'none',
        })
        reject(err)
      },
    })
  })
}

小程序的适配

自己定义导航栏,关闭原生导航栏

      "style": {
        "navigationBarTitleText": "首页",
        "navigationStyle": "custom",  // 隐藏原有的导航栏
        "navigationBarTextStyle": "white"
      }

导航栏的适配

const { safeAreaInsets } = uni.getSystemInfoSync() // 获取不同机型下刘海高度

// 为组件添加 padding值
:style="{ paddingTop: safeAreaInsets?.top + 'px' }"

ts组件的上线步骤

组件的自动导入