Taro@3.x+Vue@3.x+TS开发微信小程序,网络请求封装

参考文档

在 src/http 下创建 request.ts, 写入如下配置:

ts 复制代码
import Taro from '@tarojs/taro'
import { encryptData } from './encrypt'

console.log('NODE_ENV', process.env.NODE_ENV)
console.log('TARO_APP_PROXY', process.env.TARO_APP_PROXY)
const baseUrl = process.env.TARO_APP_PROXY

interface RequestParams {
  url: string
  method: 'OPTIONS'|'GET'|'HEAD'|'POST'|'PUT'|'PATCH'|'DELETE'|'TRACE'|'CONNECT'
  data: any
  header?: any
  timeout?: number
  loadingTitle?: string
  [key: string]: any
}
export function request (params: RequestParams) {
  const { url, method, data, header, args: { timeout = 6000, loadingTitle = '' } } = params
  Taro.showLoading({
    title: loadingTitle,
    mask: true
  })
  return new Promise((resolve, reject)=>{
    Taro.request({
      data: encryptData(data, method),
      url: baseUrl + url,
      method: method,
      timeout: timeout,
      header: {
        'content-type': 'application/json;charset=UTF-8,text/plain,*/*',
        ...header
      },
      success: (res) => { // 接口调用成功的回调函数
        console.log('success', res)
        // 具体根据后端接口返回数据接口进行resolve和reject
        if (res.data.message.code === 0) {
          resolve(res.data.data)
        } else {
          console.log('message', res.data.message.message)
          showError(res.data.message.message)
          reject({ message: res.data.message.message })
        }
      },
      fail: (res) => {
        console.log('fail', res)
        showError('请求失败')
        reject({ fail: res })
      },
      complete: (res: any) => { // 接口调用结束的回调函数(调用成功、失败都会执行)
        console.log('complete', res)
        Taro.hideLoading()
      }
    }).catch(e => {
      console.log('catch err', e)
      showError(e.errMsg)
    })
  })
}
function showError (message: string) {
  Taro.showToast({
    title: message,
    icon: 'none', // 'error' 'success' 'loading' 'none'
    duration: 2000
  })
}

在 src/http 下创建 index.ts 并导出通用请求:

ts 复制代码
import { request } from '@/http/request'

export function getAction (url: string, parameter: any, args = {}) {
  return request({
    url: url,
    method: 'GET',
    data: parameter,
    args: args
  })
}
export function postAction (url: string, parameter: any, args = {}) {
  return request({
    url: url,
    method: 'POST',
    data: parameter,
    args: args,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

在页面内进行网络请求

ts 复制代码
<script setup lang="ts">
import { ref } from 'vue'
import Taro, { useLoad, usePullDownRefresh } from '@tarojs/taro'
import { getAction } from '@/http/index'

const url = {
  detail: '/api/detail'
}
const detailData = ref()
useLoad(() => {
  getDetail()
})
usePullDownRefresh(async () => {
  await getDetail()
  Taro.stopPullDownRefresh()
})
function getDetail () {
  getAction(url.detail, { id: 1 }).then((res: any) => {
    console.log('detail', res)
    detailData.value = res.data
  }).catch((err) => {
    console.log('err', err)
  })
}
</script>
相关推荐
我的div丢了肿么办3 小时前
element-plus表格使用:filter-method过滤导致出现无数据
前端·javascript·vue.js
贾公子4 小时前
AI 内容检测 API 接入实战——异步任务、幂等键与轮询的正确写法
vue.js
星光不问赶路人4 小时前
Vue 项目类型检查:深入理解 vue-tsc --build
前端·vue.js
WeiXin_DZbishe4 小时前
基于springboot装修风格选择系统的设计与开发-计算机毕设【课程设计】77964
java·vue.js·spring boot·后端·python·php·课程设计
雪碧聊技术5 小时前
Vue 一个页面中使用多个同类组件出现“串数据“现象?一个 key 就能解决
vue.js·v-show·一个页面使用多个相同组件·解决数据错乱·v-if、key
Java小卷7 小时前
Vue3 动态表单支持弹框组件
前端·vue.js·低代码
溪语流沙7 小时前
【Web全栈进阶】前端对接新契约:信封解包 + 统一错误处理
前端·vue.js·python·状态模式·fastapi
Q26433650238 小时前
【有源码】基于SpringBoot+Vue的居民健康体检与慢病干预管理系统-面向智慧医疗的体检预约与健康知识服务平台
java·vue.js·spring boot·mysql·毕业设计·javaweb·课程设计
雪芽蓝域zzs8 小时前
Vue导入方法三种方式对比
前端·javascript·vue.js
雪芽蓝域zzs9 小时前
从零搭建【pnpm+Vue3+TS+Setup+VueRouter4+Pinia+Axios+ElementPlus (unplugin 按需)】仿若依后台
前端·vue.js