1、ts中安装mock

yarn add @types/mockjs -D

2、新建mock文件
mock
├─index.ts
├─data
|  └institution.ts

具体接口institution.ts文件

import Mock, { Random } from 'mockjs';
const list:any = [];
for (let i = 0; i < 20; i++) {
    list.push({
        id: Random.id(),
        name: Random.cname(),
        code: Random.integer(10000000,80000000),
        url: Random.url('http'),
        createTime: Random.datetime('y-MM-dd HH:mm'),
        updateTime: Random.datetime('y-MM-dd HH:mm')
    })
}
export default {
    // 查
    getList: () => {
        return {
           total: list.length,
           list: list
        }
    },
    // 增
    create: () => ({
        result: true,
        data: 'success'
    }),
    // 改
    update: () => ({
        result: true,
        data: 'success'
    })
}

index.ts文件

import Mock from 'mockjs';
import institution from './data/institution';  // 机构列表

Mock.mock('/institution/list', 'get' ,institution.getList); // 查
Mock.mock('/institution/create', 'post' ,institution.create); // 增

export default Mock
3、main.ts文件
import axios from 'axios';
if(process.env.NODE_ENV === 'development'){
  Vue.prototype.$axios = axios;
  require('./mock')
};
4、调用

axios在全局引用后 this 在ts中报错类型错误

  • (this as any)代替
  • 换用 vue-axios
    getinList(){
        (this as any).$axios.get('/institution/list').then( (res: any) => {
            this.listLoading = false;
            this.list = res.data.list;
            this.total = res.data.total;
        }).catch(()=>{})
    }
console.log(Mock)在这里插入图片描述
console.log(res)在这里插入图片描述
5、相关文档
Logo

前往低代码交流专区

更多推荐