本文主要是介绍Taro@3.x+Vue@3.x+TS开发微信小程序,网络请求封装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
参考文档
- Taro.request(option)
在 src/http
下创建 request.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_PROXYinterface RequestParams {url: stringmethod: 'OPTIONS'|'GET'|'HEAD'|'POST'|'PUT'|'PATCH'|'DELETE'|'TRACE'|'CONNECT'data: anyheader?: anytimeout?: numberloadingTitle?: string[key: string]: any
}
export function request (params: RequestParams) {const { url, method, data, header, args: { timeout = 6000, loadingTitle = '', toastDuration = 1500 } } = paramsTaro.showLoading({title: loadingTitle,mask: true})return new Promise(resolve =>{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) => { // 接口调用成功的回调函数Taro.hideLoading()console.log('success', res)if (res.data.message.code === 0) { // 具体参考接口响应的数据结构定义if (Array.isArray(res.data.data)) {resolve(res.data.data)} else {resolve({...res.data.data, success: true })}} else {console.log('message', res.data.message.message)resolve({ message: res.data.message.message, success: false })showError(res.data.message.message, toastDuration)}},fail: (res) => {Taro.hideLoading()console.log('fail', res)resolve({ message: res, success: false })showError('请求失败', toastDuration)},complete: (res: any) => { // 接口调用结束的回调函数(调用成功、失败都会执行)console.log('complete', res)}}).catch(e => {Taro.hideLoading()console.log('catch err', e)resolve({ message: e.errMsg, success: false })showError(e.errMsg, toastDuration)})})
}
function showError (message: string, duration = 1500) {Taro.showToast({title: message,icon: 'none', // 'error' 'success' 'loading' 'none'duration: duration})
}
在 src/http
下创建 index.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'}})
}
在页面内进行网络请求
<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)if (res.success) {detailData.value = res.data} else {console.log('fail message', res.message)}})
}
</script>
这篇关于Taro@3.x+Vue@3.x+TS开发微信小程序,网络请求封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!