Using Mock.js in a Vue project

foreword

With the development of the Internet industry, the separation of front and back ends has become the mainstream of the industry and is also a trend. In the development of projects driven by such a trend, we will definitely encounter such a problem. How to display data on the front-end page before the back-end interface is developed? At this time, mock.js is used.

Install Mock.js and axios

npm install --save-dev mockjs
npm install --save axios

Mock.js syntax specification

Mock.js Common Grammar Specification: Grammar Specification
Mock.js Official Website: Mock.js
insert image description here

1. Data template definition specification

Each attribute in the data template consists of 3 parts: attribute name (name), generation rule (rule), attribute value (value):

// 属性名   name
// 生成规则 rule
// 属性值   value
'name|rule': value

The attribute value is a string String

// 通过重复 string 生成一个字符串,重复次数大于等于 min,小于等于 max。
'name|min-max': string

// 通过重复 string 生成一个字符串,重复次数等于 count。
'name|count': string

The attribute value is a number Number

// 生成一个大于等于 min、小于等于 max 的整数,属性值 number 只是用来确定类型。
'name|min-max': number

// 生成一个浮点数,整数部分大于等于 min、小于等于 max,小数部分保留 dmin 到 dmax 位。
'name|min-max.dmin-dmax': number

Example:
Create a mock.js file in the src/api directory and import mock.js

// 引入mockjs
const Mock = require('mockjs');

// 生成一个用户名 随机出现1-10次
const username1 = Mock.mock({
    
    
    'username|1-10': '*'
})
// 输出:
// {username: '**'}
// {username: '*******'}

// 生成一个用户名 出现10次
const username2 = Mock.mock({
    
    
    'username|10': '*'
})
// 输出 
// {name: '**********'}

// 生成一个用户的年龄,范围在16-30之间
const age = Mock.mock({
    
    
    'age|16-30': 0
})
// 输出
// {age: 27}
// {age: 19}

// 浮点数 示例
const number = Mock.mock({
    
    
    'number1|1-5.1-10': 1,
    'number2|1-5.1-10': 1.123,
    'number3|2.1-10': 1,
    'number4|2.3': 1,
})
// 输出
/* 
 {
    number1 : 4.96537959,
    number2: 4.123741,
    number3: 2.834512422,
    number4: 2.752
 }
 */

2. Data placeholder definition specification

Placeholders just take up a position in the attribute value string and do not appear in the final attribute value.

The format of the placeholder is:

@占位符
@占位符(参数 [, 参数])

3. Commonly used placeholders

A few commonly used placeholders are listed below:

        id: '@id', //随机id
        title: '@ctitle', // 随机标题 @ctitle中文标题 @title英文标题
        name: '@cname', //随机名称 @name英文名称 @cname中文名称
        nickName: '@last', //随机昵称 @last英文昵称 @clast中文昵称
        phone: /^1[34578]\d{9}$/, //随机电话号码
        'age|11-99': 1, //年龄  属性名(age)、生成规则(rule)、属性值(value) 'age|rule': value
        address: '@county(true)', //随机地址 @county(true)省市县  @county(false)||@county()县||区||-
        email: '@email', //随机邮箱
        isMale: '@boolean', //随机性别
        createTime: '@datetime', //创建时间 可以自定义格式 @datetime(yyyy-MM-dd hh:mm:ss)
        date: '@date(yyyy-MM-dd hh:mm:ss)', // 随机生成日期 也可以自定义格式
        paragraph: '@cparagraph', // 随机描述 @cparagraph中文随机描述 @paragraph英文随机描述
        headPortrait: Random.image('200x100'), //用户头像1
        avatar() {
    
     //用户头像2
            //  # (150~200)(70-110)(70-110)红色色调
            //  # (110~170)(200-225)(200-225)蓝绿色调
            //  # (180-225)(140-255)(120-255) 跨度较大
            const a = '#' + Random.integer(180, 255).toString(16) +
                Random.integer(140, 255).toString(16) +
                Random.integer(120, 220).toString(16)
            return Random.image('100x100', a, ' png ') //dataImage
        },

insert image description here

The use of Mock.js in vue

Using mock.js to create data is actually the same as requesting the real back-end interface. It is also the server address + interface name to request. Then we need to define the interface name and the data returned by the interface. Let me talk about the general steps below. :

  1. Define interface routing, in the interface and return mock simulated data
  2. Secondary packaging interface, easy to manage
  3. The page calls this interface to obtain data

1. Define the interface route, in the interface and return the mock simulated data

Now it is equivalent to the code we wrote on the server, define the interface, and create a new index.js under the mock folder with the returned data
. This file can also be placed under the api folder or under utils, according to Depending on personal preference, define the interface in this file:

// mock.js
// 引入mockjs
const Mock = require('mockjs');
// 获取mock.Random对象
const Random = Mock.Random

// 定义一个接口名为list的接口
// window.api.baseUrl这个是我在外部文件配置的服务器地址,便于修改,你们如果没有这个需求的话,直接写上去就可以
Mock.mock(window.api.baseUrl + '/list', {
    
    
    code: 0,
    'data|10': [{
    
    
        id: '@id', //随机id
        title: '@ctitle', // 随机标题 @ctitle中文标题 @title英文标题
        name: '@cname', //随机名称 @name英文名称 @cname中文名称
        nickName: '@last', //随机昵称 @last英文昵称 @clast中文昵称
        phone: /^1[34578]\d{9}$/, //随机电话号码
        'age|11-99': 1, //年龄  属性名(age)、生成规则(rule)、属性值(value) 'age|rule': value
        address: '@county(true)', //随机地址 @county(true)省市县  @county(false)||@county()县||区||-
        email: '@email', //随机邮箱
        isMale: '@boolean', //随机性别
        createTime: '@datetime', //创建时间 可以自定义格式 @datetime(yyyy-MM-dd hh:mm:ss)
        date: '@date(yyyy-MM-dd hh:mm:ss)', // 随机生成日期 也可以自定义格式
        paragraph: '@cparagraph', // 随机描述 @cparagraph中文随机描述 @paragraph英文随机描述
        headPortrait: Random.image('200x100'), //用户头像1
        avatar() {
    
     //用户头像2
            //  # (150~200)(70-110)(70-110)红色色调
            //  # (110~170)(200-225)(200-225)蓝绿色调
            //  # (180-225)(140-255)(120-255) 跨度较大
            const a = '#' + Random.integer(180, 255).toString(16) +
                Random.integer(140, 255).toString(16) +
                Random.integer(120, 220).toString(16)
            return Random.image('100x100', a, ' png ') //dataImage
        },
        'number4|1-3.3-10': 2.456,
    }],
})

2. Secondary packaging interface

Create a new test.js under the api folder, and import our packaged index.js (mock interface) into test.js under the mock folder

import './mock/index.js'
import request from '@/utils/request'


export const getList = (() => {
    
    
    return request({
    
    
        url: '/list',
        method: 'GET',
    })
})

3. The page calls this interface to obtain data

Introduce the getList method defined above into the page, call it directly, and get our simulated data

import {
    
     getList } from "@/api/test";
export default {
    
    
  mounted() {
    
    
    this.getList();
  },

  methods: {
    
    
    async getList() {
    
    
      const res = await getList();
      console.log(res);
    },
  },
};

The data is as follows:
insert image description here
so our request is successful
insert image description here

How to control the switch of mock

We just want to use mock in the development environment, or use mock when the interface is not good

  1. Create a new .env.development to define environment variables
  2. Before defining the interface route, judge whether the current MOCK environment variable is true
module.exports = function (app) {
    
    
    if (process.env.MOCK == 'true') {
    
    
        // 定义接口及接口返回数据
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/pink_cz/article/details/126973950