vue 安装mockjs模拟接口数据
1、 创建vue项目
vue create mock-demo
2、安装mock 所需模块
1、Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 发起请求
2、mockjs 用于客户端模拟数据,实现前后端独立开发
3、JSON5是对JSON的扩展,其目的是能够在研发过程中更加容易的阅读和编写
cd mock-demo
npm install axios --save
npm install mockJs --save-dev
npm install json5 --save-dev
3、创建mock文件夹并于该文件夹下创建相关文件
1、创建user.json5 数据对象文件,具体mock数据语法参考mockjs 示例
{
id: '@id',// 随机数id
user_name: '@cname()',// 随机用户名
date: '@date()',// 随机日期
avatar: '@image("200x200","red", "#fff", "avatar")',// 随机图片
description: '@paragraph()',//随机描述
ip: '@ip()',// 随机ip
email: '@email()' // 随机邮箱
}
2、创建index.js文件
const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const JSON5 = require('json5')
function getJsonFile( filePath ) {
var json = fs.readFileSync(path.join(__dirname, './userInfo.json5'), 'utf-8')
return JSON5.parse(json)
}
module.exports = function (app){
app.get('/user/userinfo', function (rep, res) {
var json = getJsonFile('./userinfo.json5')
res.json(Mock.mock(json))
})
}
4 、在项目根目录创建vue.config.js 文件
devserver 具体配置参考 webpack 开发服务器配置
module.exports = {
devServer: {
before: require('./mock/index.js')
}
}
5 、找到vue示例页修改
helloWorld 页面路径 src/components/HelloWorld.vue,找到script 部分,添加mounted() 方法并引用axios库发起请求
mounted与created的区别:
1、created:在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图。
2、mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行操作。
import axios from 'axios'
export default {
name: 'HelloWorld',
props: {
msg: String
},
mounted() {
axios.get('user/userInfo')
.then(res => {
console.log(res)
})
}
}
6、运行项目,打开调试页面
npm run serve
页面刷新查看请求接口列表,示例代码中请求的user/userInfo 接口获取到的mock数据如下: