mock.js
Official website: Mockjs.com
Mock.js is a Mock data generator that helps separate front-end development and prototyping from back-end schedules and reduces some of the monotony, especially when writing automated tests.
Provides the following simulation functions:
- Generate simulated data from the data template
- Provide request/response emulation for Ajax requests
Project structure and dependencies
The focus here is on the flow of using AXIos to send Ajax requests and mock.js to simulate data in a Vue project.
1. After vue-CLI builds the project, install axios and mock.js
npm install -S axios
npm install -D mockjs
Copy the code
2. Create a mock folder and mock.js, and import this file in main.js
You can see a project structure like this
use
An introduction to the basic syntax of Mock
Mock. Mock (rurl, rtype, template | function (options)) rurl (optional) need to intercept the URL, can be a URL string or URL regular. For example, '/domian/list.json' rtype(optional) indicates the type of Ajax request to intercept. For example, GET, POST, PUT, and DELETE. Template (optional) represents a data template, which can be an object or a string. Data in the template each property consists of three parts: the property name, generating rules and attribute values: / / the name attribute name/value rule / / / generate rules attribute value 'name |' rule: A value such as: 'name | 1-10:1 creates an integer between 1-10, the detailed rules refer to official document function (options) (optional) is used to generate the response data as a function of the options to the request of Ajax options set, Contains url, Type, and body attributesCopy the code
1. Simulate a news list, the news object includes news title, news content and creation time, the page generates good data for us to obtain when opened
-
Write mock data in mock.js
/ / import mockjs const Mock = require('mockjs') // Get the mock.Random object const Random = Mock.Random // Mock news data, including news title, content, createdTime function produceNewsData() { let newsList = [] for (let i = 0; i < 20; i++) { let newNewsObject = { // random.ctitle (min, Max) Randomly generates a Chinese title. The default length is between 3 and 7 title: Random.ctitle(), // random.cparagraph (min, Max) Generates a Chinese paragraph randomly. The number of sentences in the paragraph is 3-7 by default content: Random.cparagraph(), // random.date () indicates the format of the generated date string, which defaults to YYYY-MM-DD createdTime: the Random date (); } newsList.push(newNewsObject) }return newList } // Intercepting the URL returns newsList Mock.mock('/mock/news', produceNewsData) Copy the code
-
In app.vue we send a GET request to get the data
<template> <div id="#app"></div> </template> <script> export default {// Create () {// This.$http.get('/mock/news'). Then (res => {console.log(res.data) // print the response data})}} </script>Copy the code
-
Run the project and open up the console and you can see that we have the simulated data.
2. Add data
If we want to test the ability to add data, mock.js can also do this. For mock. mock(URL,function(ops)), the ops argument gets the data passed.
- In mock.js we simulate an interface to add data and store it in an array.
// Add information
let projectList = []
Mock.mock('/mock/addProject'.ops= > { // Intercepts ajax requests and calls functions
console.log(ops) // What is this ops
projectList.push(ops)
})
// Get information
Mock.mock('/mock/projects', projectList)
Copy the code
- After entering the title in the input field in app.js, click Submit, and send the data to /mock/addProject. Mock. Js intercepts the request, calls function(ops), and prints out that OPS is an object with three attributes: URL, Type and body. The data we input is in the body property value, and since AXIos sends json data by default, the data inside the body is a JSON string. Change the function(ops) function to store the data in an array as a JS object. Of course, in the actual development, you can look at the data return format of the back end, and choose the operation of json to JS in the front end. Here is just a demonstration.
- Simply write a form in app. vue, input the title, click Submit and Get, and you can see that the submitted data is returned in the form of JS objects. After getting the data, you can do further operations.
<template> <div id="app"> <div> <input type="text" V-model ="title"> </button> </div> </template> <script> export default {data () { return { title: '' } }, methods: {submit () {this.$http.post('/mock/addProject', {// Add data to an object with a title attribute: this.title }) }, Get ('/mock/projects'). Then (res => {// get console.log(res.data)})}} </script>Copy the code
3. Delete data
To delete data, the id of the data is usually passed to the back end in the form of get, and the URL is: / XXX/XXX? Id =value, the backend can handle urls with different ID values. We only need to worry about how to obtain the ID. When using Mock. js, we only need to send an Ajax request with a parameter ID, and delete one item of the array according to the ID in the response function of mock.js
- The following is a mock that deletes data
let arr = [];
for (let i = 0; i < 20; i++) {
let newArticleObject = {
name: Random.cname(), // random.cname () randomly generates a common Chinese name
content: Random.csentence(5.30), // Random.csentence( min, max )
id: i,
};
arr.push(newArticleObject);
}
function list(options) {
let rtype = options.type.toLowerCase(); // Get the request type
switch (rtype) {
case "get":
break;
case "post":
let id = parseInt(JSON.parse(options.body).params.id); // Get the id of the deletion
arr = arr.filter(function(val) {
returnval.id ! = id;// Delete the object corresponding to this id from the array
});
break;
}
return {
data: arr,
}; // Returns the array, that is, returns the processed fake data
}
Mock.mock("/list"./get|post/i, list); // Get is used to request data, and POST is used to delete data
Copy the code
- The code shown in app.vue
<template> <div id="app"> <ul> <li v-for="item in data" :key="item.id"> <span>{{ item.content }}</span> <button @click="deleteList(item)"> delete </button> </li> </ul> </div> </template> <script> export default {data() {return {data: [],}; }, created() { this.setNewsApi(); }, methods: { setNewsApi: function() { this.$http.get("/list").then((res) => { this.data = res.data.data; }); }, deleteList(data) {let id = data.id; This $HTTP post ("/list ", {params: {id / / attribute shorthand},}), then ((res) = > {this. Data = res. Data. The data; Alert (data.name + "delete succeeded "); }) .catch((error) => { console.log(error); }); ,}}}; </script>Copy the code