Home > Article > Web Front-end > Detailed explanation of using vue, koa2, and mockjs to simulate data
This article mainly introduces you to the relevant information about using vue + koa2 + mockjs to simulate data. The article introduces it in detail through the example code. It has certain reference learning value for everyone's study or work. Friends who need it can follow it below. Come and learn with me.
About mockjs, the official website describes it as
1. Separation of front-end and back-end
2. You can intercept Ajax requests and return simulated response data without modifying the existing code. .
3. Rich data types
4. Simulate various scenarios through random data.
And so on.
The first step is to install the vue-cli project. There is not much to say on the Internet.
Friends who need it can refer to this article: http://www.jb51.net/article /118987.htm, the introduction is very detailed.
The second step is because the local vue accesses the local mock
1. Configure the vue proxy
The proxyTable in config/index.js, because the local node The started service accesses port 3000 by default
So configure http://localhost:3000/
proxyTable: { '/api': { target: 'http://localhost:3000/', changeOrigin: true, pathRewrite: { '^/api': '/' } }
2 in the target in mianjs of the vue project
import axios from 'axios' axios.defaults.baseURL = '/api'
The third step is to build the nodejs koa2 project
Install koa globally, not koa2. Note
1. npm install -g koa-generator
Create a folder under which HelloKoa2 is your project name
2, koa2 HelloKoa2
Enter the folder and execute the installation dependencies
3. cd HelloKoa2 and then npm install
The above completes the initialization of nodejs and then operates
4. Continue to install dependency files
npm install mockjs --save -dev //mock文件 npm install koa2-cors --save -dev //node端配置cors支持跨域用
5. Configure the app.js file. Note that the new part in the comments below is the new thing added to the original app.js file.
const Koa = require('koa') const app = new Koa() const views = require('koa-views') const json = require('koa-json') const onerror = require('koa-onerror') const bodyparser = require('koa-bodyparser') const logger = require('koa-logger') const cors = require('koa2-cors') // 新增部分处理跨域 //这里提一点题外话 假如routes文件新增一个路径就的在下面增加路劲 //假设routes新增一个user.js //新增一个user需要修改两个地方这里是一个 下面还有一个地方 //这里需要 const user = require('./routes/user') const index = require('./routes/index') const users = require('./routes/users') // error handler onerror(app) // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(cors()) // 新增部分处理跨域 app.use(json()) app.use(logger()) app.use(require('koa-static')(__dirname + '/public')) app.use(views(__dirname + '/views', { extension: 'pug' })) // logger app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) }) //这里提一点题外话 假如routes文件新增一个路径就的在下面增加路劲 //假设routes新增一个user.js //这里需要 app.use(user.routes(), user.allowedMethods()) app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) // error-handling app.on('error', (err, ctx) => { console.error('server error', err, ctx) }); module.exports = app
6. Officially use mock me Use it directly in routes/index.js
The routes/index.js file is as follows
const router = require('koa-router')() var Mock = require('mockjs') //引入mockjs const Random = Mock.Random; //引入mockjs生成随机属性的函数 random具体可以生成 //哪些东西详见http://mockjs.com/examples.html router.prefix('/index') router.get('/string', async (ctx, next) => { //116到125 是mock的第一种使用方法,这种方法随机生成1到10个数组但是每个数组的author、title等都一样 // ctx.body = await Mock.mock({ // // 属性 list 的值是一个数组,其中含有 1 到 10 个元素 // 'arr|1-10': [{ // // 属性 id 是一个自增数,起始值为 1,每次增 1 // 'id|+1': 1, // 'author|+1': Random.cname(), // 'img': Random.image('100x100'), // 'title':Random.csentence(5, 9) // }] // }) //127到141是mock的第二种方法主要使用Random函数来生成 这里生成的title、author等每个都不一样 const produceNewsData = function() { let articles = []; for (let i = 0; i < 50; i++) { let newArticleObject = { title: Random.csentence(5, 30), // Random.csentence( min, max ) author: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名 } articles.push(newArticleObject) } return { articles: articles } } ctx.body = await produceNewsData() })
Here is a little mention http://mockjs.com/examples.html Official website to see each data clearly Usage
7. Start node
npm run dev
Related recommendations:
php simulates the effects of common database operations
Use MySQL logs to simulate data change trajectories
php simulates the effects of common database operations
The above is the detailed content of Detailed explanation of using vue, koa2, and mockjs to simulate data. For more information, please follow other related articles on the PHP Chinese website!