mock 数据 , request封装

148 阅读1分钟

优医问诊  vue3 -mock数据

1. 安装  

 pnpm i vite-plugin-mock mockjs -D 

2.  vite.config.js 使用插件

import { viteMockServe } from 'vite-plugin-mock'
plugins: [
    viteMockServe({
      mockPath: './src/mock',
      localEnabled: true
    })
] 

3.  新建文件 mock文件 src/mock/index.ts

import Mock from 'mockjs'
const rules = [
  {
    url: '/patient/message/sys/list',
    method: 'get',
    timeout: 1000,
    response: () => {
      const data = []
      for (let i = 0; i < 10; i++) {
        data.push(
          Mock.mock({
            id: '@id',
            avatar: '@image("100x100")',
            title: '@ctitle(3,10)',
            content: '@ctitle(10,40)',
            createTime: '@datetime()',
            status: '@integer(0,1)',
            type: '@integer(1,3)',
          })
        )
      }
      return {
        code: 10000,
        message: '模拟数据成功',
        data
      }
    }
  }
]

export default rules 

Property 'env' does not exist on type 'ImportMeta'.

ts.config.json
{
  "compilerOptions": {
+   "types": ["vite/client"]
  }
}

uni-app hemayg 安装并配置网络请求的第三方包 

由于平台的限制,小程序项目中不支持 axios,而且原生的 wx.request() API 功能较为简单,不支 持拦截器等全局定制的功能。因此,建议在 uni-app 项目中使用 @escook/request-miniprogram 第 三方包发起网络数据请求。 

请参考 @escook/request-miniprogram 的官方文档进行安装、配置、使用 官方文档:www.npmjs.com/package/@es… 

最终,在项目的 main.js 入口文件中,通过如下的方式进行配置: vue2  vue3

//   11111111  #ifndef VUE3
import Vue from 'vue'
import App from './App'
import store from 'store/store.js'
Vue.config.productionTip = false
// 按需导入 $http 对象
import {  $http } from '@escook/request-miniprogram'
// 将按需导入的 $http 挂载到 wx 顶级对象之上,方便全局调用
// wx.$http = $http
// 在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用uni.$http = $http
// 配置请求根路径
$http.baseUrl = 'https://api-hmugo-web.itheima.net'
// 请求开始之前
$http.beforeRequest = function(options) {
    uni.showLoading({
        title: '数据加载中...'
    })
    // 在请求头中添加 Token 身份认证的字段
    // 判断请求是否为有权限的API接口
    if (options.url.indexOf('/my/') !== -1) {
        options.header = {
            // 字段的值可以直接从vuex中获取
            Authorization: store.state.userModule.token,
        }
    }}
// 请求完成之后
$http.afterRequest = function() {
    uni.hideLoading()}
// 封装的展示消息提示的方法
uni.$showMsg = function(title = '数据加载失败', duration = 1500) {
    uni.showToast({
        title,        duration,        icon: 'none'
    })}
App.mpType = 'app'
const app = new Vue({
    ...App,    store
})
app.$mount()// #endif
//    222222   xtx  #ifdef VUE3
import { useMemberStore } from '@/stores'
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'//
 添加拦截器
const httpInterceptor = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    // 2. 请求超时, 默认 60s
    options.timeout = 10000
    // 3. 添加小程序端请求头标识
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    // 4. 添加 token 请求头标识
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}
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 401错误  -> 清理用户信息,跳转到登录页 *    3.2 其他错误 -> 根据后端错误信息轻提示 *
    3.3 网络错误 -> 提示用户换网络
 */
type Data<T> = {  code: string  msg: string  result: T}
// 2.2 添加类型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success(res) {
        // 状态码 2xx, axios 就是这样设计的
        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 || '请求错误',
          })
          reject(res)
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误,换个网络试试', 
       })
        reject(err)
      },
    }) 
 })}
// 引入请求函数使用
import { http } from '@/utils/http'