zoukankan      html  css  js  c++  java
  • vue中使用mock.js

    1.安装依赖

    //使用axios发送  ajax
    npm install axios --save
    //使用mockjs产生随机数据
    npm install mockjs --save-dev
    //使用json5解决json文件,无法添加注释问题
    npm install json5 --save-dev

    2.mock.js使用

    2.1新建mock文件夹,新建userInfo.json5

    {
      "records|1-10": [
        {
          id: "@id()",//得到随机的id,对象
          username: "@cname()",//随机生成中文名字
          date: "@date()",//随机生成日期
          avatar: "@image('200x200','red','#fff','avatar')",//生成图片,参数:size, background, foreground, text
          description: "@paragraph()",//描述
          ip: "@ip()",//IP地址
          email: "@email()"//email
        }
      ]
    }

    2.2在mock文件夹,新建index.js文件

    const fs = require('fs');
    const path = require('path');
    const Mock = require('mockjs');//mockjs 导入依赖模块
    const JSON5 = require('json5');
    
    //读取json文件
    function getJsonFile(filePath) {
        //读取指定json文件
        var json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8');
        //解析并返回
        return JSON5.parse(json);
    }
    
    //返回一个函数
    module.exports = function (app) {
        // if (process.env.MOCK == 'true') {
        //监听http请求
        app.get('/api/userinfo', function (rep, res) {
            //每次响应请求时读取mock data的json文件
            //getJsonFile方法定义了如何读取json文件并解析成数据对象
            var json = getJsonFile('./userInfo.json5');
            //将json传入 Mock.mock 方法中,生成的数据返回给浏览器
            res.json(Mock.mock(json));
        });
        // }
    
    }

    2.3在项目根目录下,新建vue.config.js

    module.exports = {
      devServer: {
        before: require('./src/mock/index')//引入mock/index.js
      }
    }

    2.4发送ajax请求

    mounted() {
      axios.get('/api/userinfo') .then(res => {
          console.log(res)
      })
      .catch(err => {
          console.error(err);
       })  
    }

    3.移除mock.js

    在项目根路径新建.env.development

    MOCK = true;
  • 相关阅读:
    Jqurey 得到url参数 getUrlParam
    JQUERY获取当前页面的URL信息
    TextView,imageView属性讲解
    滑动解锁
    显示界面跳转,隐式跳转
    代码进行Relativelayout,constraintLayout布局
    代码布局-LinearLayout
    实例xml拖拽详细方法布局
    layout布局
    AS资源了解
  • 原文地址:https://www.cnblogs.com/Blogzlj/p/14774615.html
Copyright © 2011-2022 走看看