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>
相关推荐
老毛肚5 小时前
jeecgboot vue TS & 模板化 04
前端·javascript·vue.js
凌奕10 小时前
微信小程序接入微信 AI:让用户"说一句话"就能下单
微信·微信小程序·agent
卤蛋fg610 小时前
高性能 Vue 甘特图:vxe-gantt 如何秒级渲染万级任务数据
vue.js
逐光老顽童12 小时前
用 Go 实现一个 LLM 路由网关:Thompson Sampling 与自适应故障转移实践
vue.js·go
倒流时光三十年15 小时前
第十八章 搜索历史保存功能实现记录
spring boot·微信小程序
倒流时光三十年16 小时前
第十七章 投票页面增加搜索功能
spring boot·微信小程序
xkxnq17 小时前
第八阶段:工程化、质量管控与高级拓展(132天),Vue项目文档自动化:VuePress搭建组件文档(组件示例+API说明)
javascript·vue.js·自动化
静Yu18 小时前
我用Codex开发的第一个朋友圈九宫格素材小程序上线啦
微信小程序·小程序·云开发
ct97819 小时前
Promise
前端·javascript·vue.js
rising start19 小时前
五、Vue3 ref 用法 + Props 完整指南
前端·javascript·vue.js