在vue项目中使用MockJs模拟数据

版本信息:

安装mockjs

// 官网地址 http://mockjs.com/
npm i mockjs

设置

步骤一:

  1. 项目根目录下新建mock文件夹;文件夹内部新建index.js和modules文件夹;modules文件夹用于存放不同接口的数据api;index.js作为一个集合处理出口
    eg:我新建了一个user.js用于处理用户登录等功能
// user.js
import Mock from 'mockjs';
const getVerificationCode = {
    url: process.env.VUE_APP_BASE_API + '/userLogin/getVerificationCode',
    type: 'post',
    response: () => {
        console.log(" getVerificationCode response");
        return {
            code: 200,
            data: {
                code: Mock.mock('@string("number", 6)')
            }
        }
    }
};

export default {
    getVerificationCode
}

process.env.VUE_APP_BASE_API是定义在全局环境变量中的值;用来区分开发和生产

# 开发环境变量设置 .env.devlopment
# just a flag
ENV = 'development'

# base api
VUE_APP_BASE_API = '/dev-api'
# 生产环境变量设置 .env.production
# just a flag
ENV = 'production'

# base api
VUE_APP_BASE_API = 'http://你的项目api路径/'

步骤二:

通过index.js设置引入启动所有的模块

const Mock = require('mockjs');
const mockFiles = require.context('./modules', false, /\.js$/);
let mocks = [];
mockFiles.keys().forEach(key => {
    for (let item in mockFiles(key).default) {
        mocks.push(mockFiles(key).default[item])
    }
})

mocks.forEach(item => {
    Mock.mock(item.url, item.type, item.response)
})

步骤三:

在main.js中引入index.js

if (process.env.NODE_ENV === 'development') {
    require("../mock");
}

步骤四:

设置请求接口;
在utils下新建request.js

/*
 * @Descripttion: 对axios进行二次封装并添加拦截
 * @version: 
 * @Author: ahao
 * @Date: 2021-10-29 12:17:33
 * @LastEditors: ahao
 * @LastEditTime: 2021-11-02 21:55:23
 */
import axios from 'axios'
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        console.log(response)
        const res = response.data
        if (res.code !== 200) {


            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        console.log('err' + error) // for debug

        return Promise.reject(error)
    }
)

export default service

定义接口api

/*
 * @Descripttion: 
 * @version: 
 * @Author: ahao
 * @Date: 2021-10-29 14:45:58
 * @LastEditors: ahao
 * @LastEditTime: 2021-10-30 16:39:27
 */
import request from '@/utils/request'

export function login(data) {
    return request({
// 注意模拟数据时定义的接口要和mock服务里定义的接口相同
        url: 'userLogin/getVerificationCode',
        method: 'post',
        data
    })
}
export function logout(data) {
    return request({
        url: 'userLogin/logout',
        method: 'post',
        data
    })
}
export function getVerifyCode(data) {

    return request({
        url: 'userLogin/getVerificationCode',
        method: 'post',
        data,
        // 使用form data格式
        transformRequest: [
            function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret
            }
        ],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'lan': 'en'
        }
    })
}

你可能感兴趣的:(在vue项目中使用MockJs模拟数据)