Table of Contents
Preface
About mockjs, the official website describes
The first step is to install mock.js
The second step is to use mock.js
Key point 1: Mock .mock()
Key point 2: Template generation syntax:
Home Web Front-end JS Tutorial Vue+Mock.js implements detailed steps to simulate addition, deletion, modification and query of tables

Vue+Mock.js implements detailed steps to simulate addition, deletion, modification and query of tables

Jul 27, 2018 pm 02:00 PM
html5 javascript mock.js vue.js vuex

Regarding mockjs, the official website describes 1. Separation of front and rear ends 2. You can intercept Ajax requests and return simulated response data without modifying existing code. 3. Rich data types 4. Simulate various scenarios through random data.

Preface

About mockjs, the official website describes

1. Front-end and back-end separation

2. Ajax can be intercepted without modifying the existing code Request, return simulated response data.

3. Rich data types

4. Simulate various scenarios through random data.

5 The project does not take the blame (you may take the blame if you wait for the backend to provide an interface)

and other advantages, I added the last one.

The first step is to install mock.js
npm install mockjs --save-dev
Copy after login
The second step is to use mock.js
import Mock from 'mockjs'
Copy after login

Introduce it wherever you use it. I use mock.js in project src/mock/index.js

Please see the official documentation for details

Key point 1: Mock .mock()
Mock.mock( rurl?, rtype?, template|function( options ) )
Copy after login

The parameters here are all optional:

  • rurl (optional).

represents the URL that needs to be intercepted, which can be a URL string or a URL regular pattern. For example //domain/list.json/, '/domian/list.json'.

  • rtype (optional).

indicates the type of Ajax request that needs to be intercepted. For example GET, POST, PUT, DELETE, etc.

  • template (optional).

represents the data template, which can be an object or a string. For example { 'data|1-10':[{}] }, '@EMAIL'.

  • function(options)(optional).

represents the function used to generate response data.

  • options: Points to the Ajax option set for this request.

Key point 2: Template generation syntax:
  • Each attribute in the data template consists of 3 parts: attribute name, generation rules, Attribute value:

    • // Attribute name name

    • ##// Generate rule rule

    • //Attribute value value

    • 'name|rule': value

  • Use a vertical bar between the attribute name and the generated rule | separated.

  • Generation rules are optional.

  • There are 7 formats for generating rules:

    • 'name|min-max': value

    • 'name|count': value

    • 'name|min-max.dmin-dmax': value

    • ' name|min-max.dcount': value

    • 'name|count.dmin-dmax': value

    • 'name|count. dcount': value

    • 'name| step': value`

  • The meaning of the generated rules depends on the type of the attribute value. Sure.

  • The attribute value can contain @ placeholder.

  • Attribute value also specifies the initial value and type of the final value.

Give a chestnut:

Chestnut 1:

//string表示属性名
//3表示后面属性值重复次数
 Mock.mock({
  "string|3": "★"
})
Copy after login

Result:

//星星数量为3
{
  "string": "★★★"
}
Copy after login

Chestnut 2:

// num为属性名
// 生成一个大于等于1,小于等于100 的整数,属性值100只是用来确定类型
Mock.mock({
  "num|1-100": 100
})
Copy after login

Result

{
  "number": 8
}
Copy after login

Other settings

//  设置全局延时 没有延时的话有时候会检测不到数据变化 建议保留

Mock.setup({
  timeout: '300-600'
})
Copy after login

Simulated login
// Simulated login

user/login interface, the corresponding function is loginByUsername

Mock.mock(/\/user\/login/, 'post', loginByUsername)
Copy after login

When the login interface

user/loign is called, it will automatically correspond to the loginByUsername function to execute this function. This function will return data on whether the login is successful. Returning successful data means that the login is successful, otherwise it is the opposite.

mock simulated login ok

Next, we will introduce the addition, deletion, modification and query of the simulated table.

In fact, it’s almost the same.

// 用户相关
Mock.mock(/\/user\/listpage/, 'get', getUserList) //模拟分页查询用户信息接口
Mock.mock(/\/user\/remove/, 'get', deleteUser)   //模拟删除用户信息接口
Mock.mock(/\/user\/add/, 'get', createUser)     //模拟添加用户信息接口
Mock.mock(/\/user\/edit/, 'get', updateUser)   //模拟编辑用户信息接口
Copy after login

It just returns a collection of fake data after conditional query. The fake data is simulated by mock.js.

First add 60 fake users in a loop

let List = []
const count = 60

for (let i = 0; i < count; i++) {
  List.push(Mock.mock({
    id: Mock.Random.guid(),
    name: Mock.Random.cname(),
    addr: Mock.mock(&#39;@county(true)&#39;),
    &#39;age|18-60&#39;: 1,
    birth: Mock.Random.date(),
    sex: Mock.Random.integer(0, 1)
  }))
}
Copy after login

Let’s look at the function

getUserList, which returns fake data for paging condition query.

  getUserList: config => {
    const { name, page = 1, limit = 20 } = param2Obj(config.url)

    const mockList = List.filter(user => {
      if (name && user.name.indexOf(name) === -1) return false
      return true
    })

    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))

    return {
      code: 0,
      data: {
        total: mockList.length,
        users: pageList
      }
    }
  }
Copy after login

Regarding adding, deleting and modifying, you only need to return one piece of data

message="Operation successful".

The third step is to introduce the src/mock/index.js we just wrote into main.js
import &#39;./mock&#39; // simulation data 路径index.js可省略
Copy after login
The integration is now completed

Related articles:


MVC mode realizes login and addition, deletion, modification and query login

XML addition, deletion, modification and query example

Related videos :

PHP user registration and login system video tutorial

The above is the detailed content of Vue+Mock.js implements detailed steps to simulate addition, deletion, modification and query of tables. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles