Mock.js uses


introduce

Mock.jsIt is used to simulate and generate some virtual data, allowing the front-end to develop independently when the back-end interface has not been developed. We can use the real one url, mockjswhich can intercept ajaxthe request and return the set data.


1. Use

1. Installation

npm install mockjs -D

2. Create a new mockjs file

You can create new folders and files srcin the directory . Create dummy data in the file .mockindex.jsindex.js
insert image description here

3. Use mockjs virtual data

If you need to use dummy data, main.jsimport the file in the entry file mockjs.

// 导入mockjs
import './mock/index.js'

2. Create virtual data (mockjs file)

1. Import mockjs

import Mock from "mockjs";

2. Set the request delay time

Mock.setup( settings ): Configure Ajax the behavior when intercepting requests.

Mock.setup({
    
    
    // 延迟时间200毫秒
    timeout: 200,
});

3. Generate random data

  • Mock.mock( template ): Generate simulated data according to the data template. templateIndicates the data template, which can be an object or a string. Each attribute in the data template 3consists of parts: attribute name, generation rule, attribute value.
  • 'name|rule': value: attribute name name, generation rule rule, attribute value value. A vertical bar | is used to separate attribute names and generation rules.
  • 'name|min-max': array: When the attribute value is an array Array. Generate a new array by repeating the attribute value array, the number of repetitions is greater than or equal to min, less than or equal to max.
  • 'name|+1': number: When the attribute value is a number Number. The attribute value is automatically added 1, and the initial value is number.

占位符: @ Used to identify the following string is a placeholder. The placeholders refer to Mock.Randommethods in .

  • @cname: Randomly generate a common Chinese name.
  • @ctitle( min, max ): Randomly generate a Chinese title. The default is a random number between 3 and 7.
  • @integer( min, max ): Returns a random integer. min is the minimum value and max is the maximum value.

common grammar

  • “id”:“@id”
  • "star|1-2": "★" string repeated 2 times
  • "price|100-200.2-3" 2-3 decimal places
  • "data|10":[{name:"name"}] The content of the array is repeated 10 times
  • "live|1": true, randomly return true, false
  • “tel”:/13 \d{9}/,
  • “des”:function(){ return this.start+this.price}
  • "name": "@cname" indicates the Chinese name
  • "address": "@country(true)" address
  • “ip”:“@ip”,
  • "description": "@cparagraph(1, 3)" random paragraph 2-3 lines
  • "pic":@dataImage('200x100','color block image')`
// 生成subjects、grades数据
const {
    
     subjects, grades } = Mock.mock({
    
    
    "grades|3": [{
    
    
        // 属性 GradeId 是一个自增数,起始值为 1,每次增 1
        'GradeId|+1': 1,
        // @cname 随机生成一个常见的中文姓名。
        "GradeName": '@cname'
    }],
    // 随机生成一个5到10条的数组
    // 属性 subjects 的值是一个数组,其中含有 5 到 10 个元素
    "subjects|5-10": [{
    
    
        'SubjectId|+1': 1,
        // @ctitle 随机生成一句中文标题。
        SubjectName: '@ctitle(10,15)',
        // @integer( min, max )返回一个随机的整数。min最小值,max最大值
        ClassHour: '@integer(22,80)',
        GradeId: '@integer(1,3)',
    }]
});
// 给课程数组添加年级信息
subjects.forEach(r => {
    
    
    // 给每个课程信息,添加一个年级的完整信息
    r.Grade = {
    
    
        GradeId: r.GradeId,
        GradeName: grades.find(g => g.GradeId == r.GradeId).GradeName
    }
});

4. Intercept request

Mock.mock( rurl, rtype, function( options ) ): Documents the function used to generate the response data. When a request matching rurland is intercepted , the function will be executed, and the execution result will be returned as the response data.rtypeAjaxfunction(options)

  • rurl: Indicates what needs to be intercepted URL, which can be URL a string or URLa regular expression. For example /\/domain\/list\.json/, '/domian/list.json'.
  • rtype: Indicates the request type that needs to be intercepted Ajax. For example GET, POST, PUT, DELETEetc.
  • function(options): Indicates the function used to generate the response data. optionsThe properties of the object include url(complete request address), type(request type), body( postrequest body).

// 拦截查询所有年级信息的请求
Mock.mock('http://www.bingjs.com:81/Grade/GetAll', "get", () => {
    
    
    return grades;
});

// 拦截查询所有课程信息的请求
Mock.mock('http://www.bingjs.com:81/Subject/GetAll', "get", () => {
    
    
    return subjects;
});

// 拦截添加请求
Mock.mock('http://www.bingjs.com:81/Subject/Add', "post", (options) => {
    
    
    // 获取参数数据
    let obj = JSON.parse(options.body)
    let subject = {
    
    
        // 课程编号
        SubjectId: Date.now(),
        SubjectName: obj.subjectName,
        ClassHour: obj.classHour,
        GradeId: obj.gradeId
    }
    subject.Grade = Mock.mock({
    
    
        GradeId: subject.GradeId,
        GradeName: grades.find(g => g.GradeId == subject.GradeId).GradeName
    })
    subjects.push(subject)
    return true
});

// 拦截删除请求
Mock.mock('http://www.bingjs.com:81/Subject/Delete', "post", (options) => {
    
    
    // 获取课程编号
    let subjectId = JSON.parse(options.body)
    // 获取课程在数组中的位置
    let index = subjects.findIndex(r => r.SubjectId == subjectId)
    // 删除
    subjects.splice(index, 1)
    return true
});

// 拦截查询单个课程信息请求
Mock.mock(/^http:\/\/www.bingjs.com:81\/Subject\/GetSubjectById/, "get", (options) => {
    
    
    // 获取课程编号
    let id = options.url.split("?")[1].split("=")[1]
    // 根据课程编号查询指定的课程信息
    let subject = subjects.find(r => r.SubjectId == id)
    return subject
})

// 拦截修改课程信息请求
Mock.mock('http://www.bingjs.com:81/Subject/Update', "post", (options) => {
    
    
    let {
    
     subjectId, subjectName, classHour, gradeId } = JSON.parse(options.body)
    let index = subjects.findIndex(r=>r.SubjectId==subjectId)
    subjects[index].SubjectName = subjectName
    subjects[index].ClassHour = classHour
    subjects[index].GradeId = gradeId
    subjects[index].Grade.GradeId = gradeId
    subjects[index].Grade.GradeName=grades.find(g => g.GradeId == gradeId).GradeName
    return true
});

3. Send request

At this point, when the foreground sends a request to the background, it will get mockjs virtual data instead of real background data.

data() {
    
    
  return {
    
    
    // 课程数组
    Subjects: [],
    // 年级数组
    Grades: [],
    // 编辑框是否为添加状态
    isAdd: true,
    // 课程对象
    subject: {
    
    
      subjectId: 0,
      subjectName: "",
      classHour: 0,
      gradeId: 1,
    },
    // 是否显示编辑框窗口
    isShow: false,
  };
},
methods: {
    
    
  // 获取课程信息
  async getSubjects() {
    
    
    let {
    
     data } = await axios.get("http://www.bingjs.com:81/Subject/GetAll");
    this.Subjects = data;
  },
  // 获取年级信息
  async getGrades() {
    
    
    let {
    
     data } = await axios.get("http://www.bingjs.com:81/Grade/GetAll");
    this.Grades = data;
  },
  // 添加课程
  async addSubject() {
    
    
    let {
    
     data } = await axios.post("http://www.bingjs.com:81/Subject/Add", this.subject);
    if (data) {
    
    
      alert("添加成功");
      // 重新加载列表数据
      this.getSubjects();
      // 关闭添加窗口
      this.isShow = false;
      // 清空表单数据
      this.subject = {
    
    
        subjectId: 0,
        subjectName: "",
        classHour: 0,
        gradeId: 1,
      };
    }
  },
  // 删除课程
  async delSubject(SubjectId) {
    
    
    if (!confirm("确定要删除吗")) return;
    let {
    
     data } = await axios.post(
      "http://www.bingjs.com:81/Subject/Delete",
      SubjectId
    );
    if (data) {
    
    
      alert("删除成功");
      this.getSubjects();
    }
  },
  // 获取单个课程信息
  async getOneSubject(SubjectId) {
    
    
    let {
    
     data } = await axios.get( "http://www.bingjs.com:81/Subject/GetSubjectById",{
    
     params: {
    
     subjectId: SubjectId } });
    this.subject.subjectId = SubjectId;
    this.subject.subjectName = data.SubjectName;
    this.subject.classHour = data.ClassHour;
    this.subject.gradeId = data.GradeId;
    this.isAdd = false;
    this.isShow = true;
  },
  // 修改课程信息
  async updateSubject() {
    
    
    let {
    
     data } = await axios.post("http://www.bingjs.com:81/Subject/Update",
      {
    
    
        subjectId: this.subject.subjectId,
        subjectName: this.subject.subjectName,
        classHour: this.subject.classHour,
        gradeId: this.subject.gradeId,
      }
    );
    if (data) {
    
    
      alert("修改成功");
      this.getSubjects();
      this.isAdd = true;
      this.isShow = false;
    }
  },
},
created() {
    
    
  this.getSubjects();
  this.getGrades();
}

Guess you like

Origin blog.csdn.net/weixin_48353638/article/details/129625355