Vue3+ts开发学习——小兔鲜儿2

黑马的视频学习

基础架构

构建页面

  1. 安装uni-ui

uniapp官网 npm安装跟着开始说明走,直接安装就行。

  1. 跟着开始说明的自动导入模块功能设置怎么用直接使用。
  2. uni-ui-helper 安装
1
npm i -D @uni-helper/uni-ui-types

配置tsconfig.json

1
2
3
4
5
6
    "types": [
      "@dcloudio/types",
      "miniprogram-api-typings",
      "@uni-helper/uni-app-types",
      "@uni-helper/uni-ui-types"
    ]

状态管理

持久化
pinia实现

  1. API
1
2
uni.setStorageSync()
uni.getStorageSync()
  1. 存放位置:/src/stores/index.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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'

例子 [会员信息]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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)
        },
      }
    }
  },
)

主要是持久化的写法!!

数据交互

请求工具

拦截器

  • request请求
  • upload上传文件
1
2
// 实例化拦截器
uni.addInterceptor(string, object)

代码示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* 添加拦截器:
    * 拦截request请求
    * 拦截uploadFile文件上传
* TODO:
    * http开头需要拼接地址
    * 请求超时
    * 添加小程序端请求头标识
    * 添加token请求头标识 
**/

import { useMemberStore } from "@/stores"

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

//添加拦截器
const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        // http开头需要拼接地址
        if (!options.url.startsWith('http')) {
            options.url = baseURL + options.url
        }
        // 请求超时
        options.timeout = 10000
        // 添加小程序端请求头标识
        options.header = {
            ...options.header,
            'source-client': 'miniapp',
        }
        //添加token请求头标识
        const memberStore = useMemberStore()
        const token = memberStore.profile?.token
        if (token) {
            options.header.Authorization = token
        }
        // console.log(options)
    },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)


/**
 * 请求函数
 * @param UniApp.RequestOptions
 * @returns Promise
 * 1. 返回Promise对象
 * 2. 请求成功
 *  2.1 提取核心数据res.data
 *  2.2 添加类型,支持泛型
 * 3. 请求失败
 *  3.1 网络错误 -> 提示用户换网络
 *  3.2 401错误 -> 清理用户信息,体专登录页
 *  3.3 其它错误 -> 根据后端错误信息轻提示
 */

interface Data<T> {
    code: string
    msg: string
    result: T
}

// 2.2 添加类型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
    //1. 返回Promise对象
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            // 2. 请求成功
            success(res) {
                // 状态码 2xx
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    // 2.1 提取核心数据res.data
                    resolve(res.data as Data<T>)
                } else if (res.statusCode === 401) {
                    // 401错误 -> 清理用户信息,体专登录页
                    const memberStore = useMemberStore()
                    memberStore.clearProfile()
                    uni.navigateTo({ url: '/pages/login/login' })
                    reject(res)
                } else {
                    // 其他错误
                    uni.showToast({
                        icon: 'none',
                        title: (res.data as Data<T>).msg || '请求错误'
                    })
                }
            },
            fail(err) {
                uni.showToast({
                    icon: 'none',
                    title: '网络错误,换个网络试试'
                })
                reject(err)
            }
        })
    })
}
0%