mock.js

Mockjs.com/ MockJS is used to simulate the generation of virtual data, allowing the front-end to be developed independently before the back-end interface is developed. We can use a real URL, and MockJS can intercept ajax requests and return predefined data.

use

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 constructs the project, install axios and mock.js
npm install -S axios
npm install -D mockjs
Copy the code
  1. Create a new mock.js folder in your project to format the mock data to produce.

// add mockjs const mock = require('mockjs'Mock.Random const Random = mock.Random // Mock news data, Includes news title, content, createdTime const produceNewsData =function () {
  let newsList = []
  for (let i = 0; i < 20; i++) {
    letNewNewsObject = {title: random.ctitle (), // random.ctitle (min, Max) Random.cparagraph(), // random.cparagraph (min, Max) generates a paragraph with a default createdTime of 3 to 7: Random.date() // random.date () indicates the format of the generated date string, which defaults to YYYY-MM-DD; } newsList.push(newNewsObject) }returnNewList} // Request the URL to return newsList mock. Mock ('/mock/news', produceNewsData) // Details on how to use this APICopy the code
  1. Introducing the mock.js file in main.js indicates that we are using the data generated in it.
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'

require(./mock.js)
Copy the code
  1. In app.vue we send a GET request to get the data
// App.vue
<template>
    <div id="#app"></div>
</template>
<script>
import axios from 'axios'/ / introduce axiosexportDefault {// Get the news list when mountingmounted() {
        axios.get('/mock/news').then(res => {// url is console.log(res.data) // print the response data})}} </script>Copy the code

Mock.mock()

Mock.mock( rurl, rtype, template|function(Options) rURL Optional. Indicates the URL to be intercepted. It can be a URL string or A URL re. For example,'/domian/list.json'. Rtype optional. Represents the type of Ajax request to intercept. For example, GET, POST, PUT, and DELETE. The template is optional. Represents a data template, which can be an object or a string. Each attribute in a data template consists of three parts: attribute name, generated rule, and attribute value: // Attribute name // Generated rule // Attribute value value'name|rule': value Example:'name|1-10':1 produces an integer between 1 and 10. For details, see the official documentationfunctionOptional (options). Represents the function used to generate the response data. Options points to the Ajax options set for this request, containing the URL,typeAnd bodyCopy the code

Increase the data

Mock. Mock (URL,function(ops)). The ops argument gets the data to be passed.

// App.vue
<template>
  <div id="app">
    <div>
      <input type="text" v-model="title">
      <button type="button" @click="submit"</button> <buttontype="button" @click="getProjects"</button> </div> </div> </template> <script> import axios from'axios'
export default {
  data () {
    return {
      title: ' '
    }
  },
  methods: {
    submit () {
      axios.post('/mock/addProject'}, {// add data interface, data is an object, has a title attribute title: this.title})},getProjects () {
      axios.get('/mock/projects'). Then (res = > {/ / get data to the console. The log (res) data)})}}} < / script >Copy the code

In mock.js we simulate an interface to add data and store it in an array.

// mock. Js // add informationlet projectList = []
Mock.mock('/mock/addProject'Projectlist.push (ops)}) // Get information mock.mock ('/mock/projects', projectList)
Copy the code

// mock. Js // add informationlet projectList = []
Mock.mock('/mock/addProject', ops => {// Intercept ajax requests, Ops = json.parse (ops.body) projectList.push(ops)})'/mock/projects', projectList)
Copy the code


Delete the 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. In practice, the backend can handle urls with different ID values very well. We only need to worry about how to get the ID. Mock. Mock (‘/ Mock /delete’), when axios.get() is used: