vue3+ts项目里使用mockjs

1.安装mockjs

cnpm install mockjs --save-dev

2.创建mock文件夹,创建index.ts、types.ts 以及你需要使用到的模块的.ts文件

vue3+ts项目里使用mockjs

inde.ts文件代码:

import Mock from 'mockjs'
import { MockParams } from './types'
import api from './api'

// 需要遍历的请求
const mocks = [...api]

// 设置200-2000毫秒延时请求数据
Mock.setup({
    timeout: '200-1000'
})

// 接口拦截
export function mockRequest() {
    let i: MockParams
    for (i of mocks) {
        Mock.mock(new RegExp(i.url), i.type || 'get', i.response)
    }
}

types.ts文件代码:

// 定义参数类型
export interface MockParams {
    url: string
    type: string
    data?: any
    params?: any
    response(option?: any): Record<string, unknown>
}

api.ts文件代码:

// get请求从config.url获取参数,post从config.body中获取参数
function paramObj(url: any) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
        '"}'
    )
}

const api = [
    // 登录接口
    {
        url: '/user/login',
        type: 'post',
        response: (config: any) => {
            // const {account} = paramObj(config.url)
            const {account} = JSON.parse(config.body)
            if (account === 'admin') {
                return {
                    code: 200,
                    message: '操作成功',
                    data: {
                        token: 'admin'
                    }
                }
            }
            return {
                code: 401,
                message: '用户信息错误,请重试~',
                data: {}
            }
        }
    }
]
export default api

3最后在main.ts引入

/**
 * 测试环境下 引入自定义的mockRequest
 * 因为mockRequest不是默认导出的:export default{}
 * 所以引入时需要加大括号,这种可以引入多个
 */
if (process.env.NODE_ENV === 'development') {
    const {mockRequest} = require('@/mock')
    mockRequest()
}

4在shims-vue.d.ts中添加声明

declare module 'mockjs'

详细的配置参考自(侵删):

https://www.jianshu.com/p/f8c5c245f904

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注