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

6 篇文章 0 订阅

参考文档

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_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 = '', toastDuration = 1500 } } = params
  Taro.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 = {}, args = {}) {
  return request({
    url: url,
    method: 'GET',
    data: parameter,
    args: args
  })
}
export function postAction (url: string, parameter = {}, 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'

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>
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序中,我们可以使用下拉刷新组件来刷新页面。在 Taro + Vue3 中,可以通过在页面的配置对象中添加 `enablePullDownRefresh: true` 来启用下拉刷新功能。 具体步骤如下: 1. 在页面的配置对象中添加 `enablePullDownRefresh: true`。 ```javascript export default { enablePullDownRefresh: true, // ... } ``` 2. 在页面的方法中添加 `onPullDownRefresh` 方法,该方法会在用户下拉刷新时触发。 ```javascript export default { enablePullDownRefresh: true, onPullDownRefresh() { // 执行刷新操作 }, // ... } ``` 3. 在 `onPullDownRefresh` 方法中编写刷新操作的代码。例如,我们可以重新请求数据,并更新页面渲染。 ```javascript export default { enablePullDownRefresh: true, async onPullDownRefresh() { // 重新请求数据 const newData = await this.fetchData() // 更新页面渲染 this.dataList = newData // 停止下拉刷新 Taro.stopPullDownRefresh() }, // ... } ``` 4. 最后,在页面中添加下拉刷新组件。可以使用 Taro UI 的 `AtPullDownRefresh` 组件,也可以自定义组件。 ```html <template> <!-- 使用 Taro UI 的 AtPullDownRefresh 组件 --> <view> <at-pull-down-refresh v-model="isRefreshing" color="#999" background-color="#f7f7f7" bind:refresh="onPullDownRefresh" > <view class="status" slot="status"> {{ isRefreshing ? '正在刷新...' : '下拉刷新' }} </view> </at-pull-down-refresh> <!-- 渲染数据列表 --> <view v-for="item in dataList" :key="item.id"> {{ item.title }} </view> </view> </template> ``` 以上就是在 Taro + Vue3 中实现微信小程序下拉刷新的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值