Several front-end analog data usage schemes

The Role and Necessity of Simulation Data

1. Static page development needs to simulate data filling to see the style
2. Self-test needs data in various scenarios, such as empty data, slow network, various states of data, etc. 3.
When programming for leaders, you can have something to show to leaders earlier, Requirements need to be changed as soon as possible (the humbleness of the coder)
4. Reduce the front-end joint debugging time. As long as the interface document is correct, the joint debugging can be done after a few glances. If a bug occurs, it is also the back-end.
5. When bugs are modified and requirements change, You don’t need to connect to the backend to go around in circles (loading is very annoying when the interface is slow)
6. I will add it later when I think of it

Several simulation data usage scenarios

  1. Simply and crudely written in the code
  2. Use promise to encapsulate the interface to customize the return
  3. Start the backend service locally
  4. use mockjs
  5. Use nodejs to simulate a server
  6. Use YApi, ApiPost, postman and other API debugging and interface documentation tools

Write directly in the business code

Advantages:
1. Easy to use.

Disadvantages:
1. The code is too bloated if it is not deleted, and it has to be rewritten when it is deleted.
2. It is not asynchronous, and the code may have timing bugs when actually using asynchronous data

Recommended usage scenarios:
1. The project is very simple

User guide: as long as you have your hands

// 用脚的写法
let data = null;
// 用的时候打开
// data = [
// 	{ label: 1, name:1}
// ]
// 用的时候注释掉下面,不用的时候注释掉上面
await axios.get({
    
    
	url: `/getData`,
}).then(rsp => {
    
    
	data = rsp.data;
}).catch(rsp=>{
    
    
	reject(rsp);
});
this.originData = data;

// 用手写
let data = null;
if(process.env.NODE_ENV == 'development'){
    
    
	data = [
		{
    
     label: 1, name:1}
	];
} else {
    
    
	await axios.get({
    
    
		url: `/getData`,
	}).then(rsp => {
    
    
		data = rsp.data;
	}).catch(rsp=>{
    
    
		reject(rsp);
	});
}
this.originData = data;

// 数据太多了,放到同级目录下的mock.json里
let data = null;
if(process.env.NODE_ENV == 'development'){
    
    
	data = await axios.get({
    
    
		url: `./mock.json`,
	});
} else {
    
    
	await axios.get({
    
    
		url: `/getData`,
	}).then(rsp => {
    
    
		data = rsp.data;
	}).catch(rsp=>{
    
    
		reject(rsp);
	});
}
this.originData = data;

Use promise to encapsulate interface to call custom return

Advantages:
1. Easy to use
2. Compared with the first method, the simulated data is extracted from the business code, and the code is cleaner

Disadvantages:
1. It is the same as directly writing in the business code

Recommended usage scenarios:
1. The project is very simple

Usage guide: The api call is written in the api.js file in the same directory

// api.js代码示例
export default {
    
    
    // 获取数据
    getData(option) {
    
    
        return new Promise(resolve => {
    
    
        	if(process.env.NODE_ENV == 'development'){
    
    
        		resolve({
    
    
        			"code": 0,
			        "data":[]
				});
			   return;
			}
            axios.get({
    
    
                url: `/getData`,
                ...option
            }).then(rsp => {
    
    
                resolve(rsp);
            }).catch(rsp=>{
    
    
				reject(rsp);
			});
        });
    },
}
// 业务代码中使用
import Api from './api';
...
let options = {
    
     data: {
    
    } };
let data = await Api.getData(options);
console.log(data);

Start the backend service locally

Advantages:
1. The real interface call saves the steps of joint debugging after debugging.

Disadvantages:
1. You need to understand the backend. This machine has a complete set of backend development software.
2. If the computer configuration is not enough, it will be relatively stuck, because the backend IDE is relatively heavy.
3. The backend needs to be developed first.

Recommended usage scenarios:
1. Personal projects
2. Small companies, both the front end and the front end are the same person

User guide: learn the backend, the author is also learning

use mockjs

Advantages:
1. Easy to use

Disadvantages:
1. It is not asynchronous and needs to be added manually.
2. It does not support file operations, all interfaces will be intercepted, and the format of asynchronously loaded files will be changed (such as mapbox image loading), resulting in file parsing failure

Recommended usage scenarios:
1. Projects that do not have a lot of asynchronous file loading can be used

user's guidance

1. Installation

npm install mockjs

2. Introduce in the entry file (such as vue's main.js)

// 开发环境才启用,当然也可以不这么写,先部署到测试环境给产品经理跟UI看看效果
if(process.env.NODE_ENV == 'development'){
    
    
    require('/mock/index.js');  // 自定义js文件地址
}

3. Use (in mock/index.js)

// 引入
import Mock from 'mockjs';
// 假设有多个代理前缀
const baseUrl= {
    
    
    server1: '/system',
    server2: '/user',
}
// 接口拦截默认是全字符串匹配,RegExp ".*",是为了避免接口后带了query
Mock.mock(RegExp(server.server1+ '/login' + ".*"), function (options) {
    
    
	/*
		options的参数:
		type 请求类型,
		url 包括了query, 
		body post请求的body
	*/
	const {
    
     body, url } = options;
    return {
    
    
        "code": 0,
        "data":{
    
    
			"userName": body.userName
		}
    }
})
Mock.mock(RegExp(server.server2+ '/getSomething' + ".*"), function (options) {
    
    
	const {
    
     body, url } = options
	let data = [];
	for(let i = 0; i < 10; i++){
    
    
		data.push({
    
    
			"label": "哈哈" + i,
			"value": parseInt( Math.random() * 100 )
		})
	}
    return {
    
    
        "code": 0,
        "data": data
    }
})
export default Mock;

Here we only introduce the interface interception of mockjs, mockjs can also generate simulated data (Math.random is usually enough), for more advanced use, please go to the official website address

Use nodejs to simulate a server

Advantages:
1. Real interface calls
2. Can be deployed to the server for demonstration
3. Support file operations such as uploading and downloading

Disadvantages:
1. You need to start an additional node service
2. You need to learn node
3. As a front-end, you should learn nodejs, so the above are not considered disadvantages

Recommended usage scenarios:
1. Relatively complex projects
2. If the company has basic scaffolding, use it after introduction

Install nodejs (node ​​offline package installation on Linux)

1. Go to the official website to pick a suitable nodejs version. What is appropriate? Just to see if your linux processor is arm architecture or x86 architecture
linux command:

 lscpu

insert image description here

insert image description here
2. Upload to linux and decompress (if put in home)

 tar -zxvf node-xxx.tar.xz -C /home/nodejs 

3. Set the global node command

ln -s /home/nodejs/bin/npm /usr/local/bin/ 
ln -s /home/nodejs/bin/node /usr/local/bin/

4. Finally, take a look at node -v and npm -v. If it fails, either the node version is wrong or the path is wrong. Delete the soft link and repeat the above operation

// 删除软链指令:
rm -rf /usr/local/bin/node
rm -rf /usr/local/bin/npm

5. It is best to install a pm2 when using node as a server. PM2 is a node process management tool. The installation is as follows

// 最好跟node安装包放一块 cd /home/nodejs后执行
npm install pm2
// 加个软链把pm2设置为全局命令
ln -s /home/nodejs/node_modules/pm2/bin/node /usr/local/bin/
// 在windows上面直接 npm install pm2 -g ,不过感觉window上没必要用pm2,开发环境用nodemon带热更新方便点

Install express, nodemon

// express是node服务器框架,使用简单
npm install express
// nodemon是一个可以监听文件变化热更新服务器的插件,
npm install nodemon -g
// 在package.json同目录下创建一个nodemon.json文件,下面是官网的默认配置
{
    
    
    "restartable": "rs",
    "ignore": [
        ".git",
        ".svn",
        "node_modules/**/node_modules"
    ],
    "verbose": true,
    "execMap": {
    
    
        "js": "node --harmony"
    },
    // 这里写要监听的文件路径
    "watch": [
        "./mock-server/index.js",
        "./mock-server/monitor.js",
        "./mock-server/warn.js"
    ],
    "env": {
    
    
        "NODE_ENV": "development"
    },
    "ext": "js json"
}

Use express to develop mock services

Create a mock folder and server.js file in the root directory of the vue project, and create router1.js, router2.js, and router3.js in
the
mock

const express = require('express');
const server = express();
// 引入并使用路由,使用router可以根据后端服务
// 注意: 代码里面的路径跟你在哪启动命令有关,原理是:在哪里启动服务,那里就是根目录
// 相对路径指的是相对于根目录的路径。详细情况到nodejs官网看
const router1= require('./mock/router1');
// 路由前缀
server.use('/router1', indexRouter);
const router2= require('./mock/router2');
server.use('/router2', warnRouter);
// 前缀也可以是一样的,为了区分模块把接口写在不同文件中更合适
const router3= require('./mock/router3');
server.use('/router2', router3);
// 监听端口号为8888
server.listen(8888);

2. router file

const express = require('express');
const router = express.Router();
const pre = "/api";
const fs = require('fs');
// 简单使用
router.post(pre + '/getData', function (req, res) {
    
    
    res.json({
    
    data:{
    
    a:1}});
})
// 根据参数返回
router.post(pre + '/getDataByPage', function (req, res) {
    
    
    let params = req.body;
    let records = [];
    let citys = ["西安市", "成都市", "重庆市", "新疆维吾尔自治区", "东莞市"];
    for (let i = 0; i < pageSize; i++) {
    
    
        let timeNum = parseInt(Math.random() * 9);
        records.push({
    
    
            "citys": citys[parseInt(Math.random() * 6)],
            "level": parseInt(Math.random() * 3 + 1),
            "sendMsgTime": replaceStr(params.startTime, 12, timeNum + 1)
        })
    }
    res.json({
    
    
        "code": "200",
        "data": {
    
    
            "page": params.page,
            "records": records,
            "pageSize": params.pageSize,
            "total": 36
        },
        "msg": "success"
    })
})
// 读取json文件的方式
router.get(pre + '/getDataFromJson', function (req, res) {
    
    
    let srcObj = fs.readFileSync('./mock/some.json', {
    
    encoding:'utf-8'});
    res.json( JSON.parse(srcObj) );
})

module.exports = router

3. Start the node service

// node 启动
node server.js
// nodemon启动
nodemon server.js
// pm2启动
pm2 start server.js

4. Configure proxy in vue.config.js (take vue-cli3 as an example)

module.exports = {
    
    
	// 省略其它配置
	devServer: {
    
    
        proxy: {
    
    
            '/api': {
    
    
                target: 'localhost:8888',
                // 重写前缀为空
                // pathRewrite: path => {
    
    
                //     return path.replace('/api', '');
                // },
                // websocket开上,但是使用时容易把vue的开发服务器击穿
                ws: true,
                // 跨域开上
                changeOrigin: true
            },
        },
        open: true
    }
}

Use YApi, ApiPost, postman and other API debugging and interface documentation tools

Advantages:
1. Generally, it is written by the backend. If it is written well, the frontend does not need to make simulation data by itself.
2. It can be used as an interface document.

Disadvantages:
1. Need a reliable back-end team
2. Need some learning costs

Usage guide: There is nothing to say about the use of the tool, just go to the official website to find out.

Summarize

1. If the back-end team is reliable (the back-end is the most reliable), then choose a tool for the back-end.
2. If the project is simple, then use mockjs
3. If you want the best effect, then use nodejs to write a service
4. If you want to be lazy, write it in the code promise
5. Don’t write it directly in the business code, you must write it Just don’t delete, comment out or compile according to the environment, the ugly code is ugly

Guess you like

Origin blog.csdn.net/qq_38217940/article/details/123216299