学习笔记 | 微信小程序项目day02

news/2024/7/20 4:34:42 标签: 小程序, uni-app

今日学习内容

  • 安装uni-ui跟@uni-helper/uni-ui-types
  • 配置pinia持久化
  • 请求工具类的拦截器
  • 请求工具类的请求函数

安装uni-ui跟@uni-helper/uni-ui-types

npm install -g cnpm --registry=https://registry.npmmirror.com
npm set registry https://registry.npmmirror.com
npm i -g pnpm
npm i @dcloudio/uni-ui

//配置ts类型
pnpm i -D @uni-helper/uni-ui-types

配置uni-ui自动导入

设置pinia持久化

1、新建stores/index.ts

import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'

// 创建 pinia 实例
const pinia = createPinia()
// 使用持久化存储插件
pinia.use(persist)

// 默认导出,给 main.ts 使用
export default pinia

// 模块统一导出
export * from './modules/member'

2、在新建store的时候加上持久化的配置

import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useMemberStore = defineStore(
  'member',
  () => {
    // 会员信息
    const profile = ref<any>()

    // 保存会员信息,登录时使用
    const setProfile = (val: any) => {
      profile.value = val
    }

    // 清理会员信息,退出时使用
    const clearProfile = () => {
      profile.value = undefined
    }

    // 记得 return
    return {
      profile,
      setProfile,
      clearProfile,
    }
  },
  // TODO: 持久化
  {
    //网页端的写法
    // persist: true,
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },
  },
)

请求工具类的拦截器

配置拦截器并添加

import { useMemberStore } from "@/stores"



//api请求地址
const apiUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'


//初始化拦截器配置
const httpInterceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //如果不是http请求开头的则需要拼接apiUrl
    if (!options.url.startsWith('http')) {
      options.url = apiUrl + options.url
    }
    //配置请求超时时间
    options.timeout = 10 * 1000
    //添加请求头

    options.header = {
      ...options.header,
      'source-client': 'miniapp'
    }

    //添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }


  }
}

//添加拦截器  request uploadFile   httpInterceptor是配置
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

使用

<script setup lang="ts">
import { useMemberStore } from '@/stores'
import '@/utils/http'

const memberStore = useMemberStore()



const getData = () => {
  uni.request({
    method: 'GET',
    url: '/category/top',
    header: {

    },
  })
}

</script>

<template>
  <view class="my">
    <view>会员信息:{{ memberStore.profile }}</view>
    <button @tap="
      memberStore.setProfile({
        nickname: '黑马先锋',
        token: '123'
      })
      " size="mini" plain type="primary">
      保存用户信息
    </button>
    <button @tap="memberStore.clearProfile()" size="mini" plain type="warn">清理用户信息</button>
    <button @tap="getData()" size="mini" plain type="warn">发起请求</button>

  </view>
</template>

<style lang="scss">
//
</style>

请求工具类的请求函数

import { useMemberStore } from '@/stores'

//api请求地址
const apiUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

//初始化拦截器配置
const httpInterceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //如果不是http请求开头的则需要拼接apiUrl
    if (!options.url.startsWith('http')) {
      options.url = apiUrl + options.url
    }
    //配置请求超时时间
    options.timeout = 10 * 1000
    //添加请求头

    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }

    //添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}

//添加拦截器  request uploadFile   httpInterceptor是配置
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)


//配置请求函数


//step.1 先定义出与后端约定返回的数据格式
interface Data<T> {
  code: string
  msg: string
  result: T
}

//step.2 定义出http 使用泛型
export const http = <T>(options: UniApp.RequestOptions) => {
  //返回Promise
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //step.3 响应成功
      success(res) {
        //如果状态码是2xx || 3xx 才会进入resolve
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          //清理用户信息并跳转到登录页
          const memberStore = useMemberStore()
          memberStore.clearProfile()

          //跳转登录页
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          //其他错误,进行提示
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求错误',
            icon: 'none',
            mask: true
          })
          reject(res)
        }

      },
      //step.4 响应失败
      fail(err) {
        reject(err)
        uni.showToast({
          icon: 'none',
          title: '网络错误,换个网络试试'
        })
      }
    })
  })
}

测试请求路径不存在

<script setup lang="ts">
import { useMemberStore } from '@/stores'
import { http } from '@/utils/http'

const memberStore = useMemberStore()

const getData = async () => {
  const res = await http<string[]>({
    method: 'GET',
    url: '/category/top123',
    header: {},
  })
  console.log(res)
}
</script>

<template>
  <view class="my">
    <view>会员信息:{{ memberStore.profile }}</view>
    <button @tap="
      memberStore.setProfile({
        nickname: '黑马先锋',
        token: '123',
      })
      " size="mini" plain type="primary">
      保存用户信息
    </button>
    <button @tap="memberStore.clearProfile()" size="mini" plain type="warn">清理用户信息</button>
    <button @tap="getData()" size="mini" plain type="warn">发起请求</button>
  </view>
</template>

<style lang="scss">
//
</style>

http://www.niftyadmin.cn/n/5434758.html

相关文章

使用 GitHub Actions 通过 CI/CD 简化 Flutter 应用程序开发

在快节奏的移动应用程序开发世界中&#xff0c;速度、可靠性和效率是决定项目成功或失败的关键因素。持续集成和持续部署 (CI/CD) 实践已成为确保满足这些方面的强大工具。当与流行的跨平台框架 Flutter 和 GitHub Actions 的自动化功能相结合时&#xff0c;开发人员可以创建无…

Go语言-关于 go get 和 go install

Go语言-关于 go get 和 go install 一直以来&#xff0c;我们通常都是通过 go get 来下载并安装包的。但从 Go 1.16 起&#xff0c;不推荐通过 go get 来安装包&#xff08;主要是说安装可执行文件&#xff09;&#xff0c;也就是说&#xff0c;go get 应该只是用来下载包&…

PC电脑如何使用HDMI连接小米电视当显示屏

使用HDMI连接好当时和电脑&#xff0c;HDMI2.0会更清晰&#xff1b;小米电视会自动弹窗提示你有HDMI 接口连接&#xff0c;或者你进入信号源进行选择即可&#xff1b;需要平时我们电脑的显示器正常连接&#xff0c;然后按 win p &#xff0c;选择 扩展 屏幕&#xff1b; 进入设…

如何实现图片上传至服务器

在绝大多数的项目中都会涉及到文件上传等&#xff0c;下面我们来说一下技术派中是如何实现原生图片上传的&#xff0c;这个功能说起来简单&#xff0c;但其实对于技术还是有考验的。图片的上传涉及到IO读写&#xff0c;一个文件上传的功能&#xff0c;就可以把IO流涉及到的知识…

MySQL实战:监控

监控指标 性能类指标 名称说明QPS数据库每秒处理的请求数量TPS数据库每秒处理的事务数量并发数数据库实例当前并行处理的会话数量连接数连接到数据库会话的数量缓存命中率Innodb的缓存命中率 功能类指标 名称说明可用性数据库是否正常对外提供服务阻塞当前是否有阻塞的会话…

【计算机网络】基本概念

基本概念 IP 地址端口号协议协议分层封装分用客户端服务器请求和响应两台主机之间的网络通信流程 IP 地址 概念&#xff1a;IP 地址主要是用于唯一标识网络主机、其他网络设备&#xff08;如路由器&#xff09;的网络地址。简单来说&#xff0c;IP地址用来唯一定位主机。格式&…

Blocks —— 《Objective-C高级编程 iOS与OS X多线程和内存管理》

目录 Blocks概要什么是BlocksOC转C方法关于几种变量的特点 Blocks模式Block语法Block类型 变量截获局部变量值__block说明符截获的局部变量 Blocks的实现Block的实质 Blocks概要 什么是Blocks Blocks是C语言的扩充功能&#xff0c;即带有局部变量的匿名函数。 顾名思义&#x…

FFplay使用滤镜添加字幕到现有视频显示

1.创建字幕文件4k.srt 4k.srt内容: 1 00:00:01.000 --> 00:00:30.000 日照香炉生紫烟2 00:00:31.000 --> 00:00:60.000 遥看瀑布挂前川3 00:01:01.000 --> 00:01:30.000 飞流直下三千尺4 00:01:31.000 --> 00:02:00.000 疑是银河落九天2.通过使用滤镜显示字幕在视…