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数据如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值