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>
相关推荐
像我这样帅的人丶你还12 小时前
别再让JS耽误你进步了。
css·vue.js
@yanyu66612 小时前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
王霸天12 小时前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
悟空瞎说12 小时前
深入 Vue3 响应式:为什么有的要加.value,有的不用?从设计到源码彻底讲透
前端·vue.js
SuperEugene15 小时前
前端通用基础组件设计:按钮/输入框/弹窗,统一设计标准|组件化设计基础篇
前端·javascript·vue.js·架构
我命由我1234515 小时前
在 React 项目中,可以执行 npm start 命令,但是,无法执行 npm build 命令
前端·javascript·vue.js·react.js·前端框架·json·ecmascript
aidou131415 小时前
Vue3自定义实现日期选择器(可单选或多选)
前端·javascript·vue.js·日期选择器·transition
忆琳16 小时前
Vue3 优雅解决单引号注入问题:自定义指令 + 全局插件双方案
vue.js·element
px不是xp16 小时前
微信小程序组件化开发最佳实践
微信小程序·小程序·notepad++
曲江涛16 小时前
微信小程序 摄像头 授权同页面丝滑调用
微信小程序