1. Install mock in TS
npm install @types/mockjs -D
npm install mockjs -D
Copy the code
2. Create a mock file
/ / SRC folder mock ├ ─ index. The ts ├ ─ data | └ table. The tsCopy the code

Table. Ts interface file

import { Random } from 'mockjs'
interface ListType {
    id: number,
    name: string,
    code: number,
    province: string,
    date: string
}
const dataList: Array<ListType> = [];
for (let i = 0; i < 100; i++) {
    dataList.push({
        id: i,
        name: Random.cname(),
        code: Random.integer(100000, 800000),
        province: Random.province(),
        date: Random.date(),
    })
}
export default {
    getList: (params: any) => {
        const info = JSON.parse(params.body);
        const [index, size, total] = [info.pageIndex - 1, info.pageSize, dataList.length]
        const len: any = total / size
        const totalPages: number = len - parseInt(len) >= 0 ? parseInt(len) + 1 : len
        const newDataList: Array<ListType> = dataList.slice(index * size, (index + 1) * size)
        return {
            total: dataList.length,
            data: newDataList,
            totalPages: totalPages
        }
    },
    update: (params: any) => {
        const info = JSON.parse(params.body);
        dataList[info.index] = info.data
        return {
            result: true,
            data: 'success'
        }
    },
    delete: (params: any) => {
        const info = JSON.parse(params.body);
        dataList.splice(info.index, 1);
        return {
            result: true,
            data: 'success'
        }
    }
}
Copy the code

Index. Ts file

import Mock from 'mockjs'
import table from './data/table'
​
Mock.mock('/table/getList', 'post', table.getList)
Mock.mock('/table/update', 'post', table.update)
Mock.mock('/table/delete', 'post', table.delete)
​
export default Mock
Copy the code
3. Main. ts file
if (process.env.NODE_ENV === 'development') {
    require ('./mock/index.ts')
}
Copy the code
4. Request encapsulation
Import request from '@/utils/request' // export function getTableList(params: any): Promise<any> { return request({ url: '/table/getList', method: 'post', data: params }) } export function deleteTableList(params: any): Promise<any> { return request({ url: '/table/delete', method: 'post', data: params }) } export function updateTableList(params: any): Promise<any> { return request({ url: '/table/update', method: 'post', data: params }) }Copy the code
5, call
import { getTableList, deleteTableList, updateTableList } from "@/api/api";
getTableList() {
  let params = {
    pageIndex: this.pageIndex,
    pageSize: this.pageSize,
  };
  getTableList(params).then((res: any) => {
    this.tableData = res.data;
    this.total = res.total;
  });
},
Copy the code
Project Address:Github.com/bo2bo/vue3-…