zoukankan      html  css  js  c++  java
  • 在vue项目中mock数据

    第一步:安装:

    在命令行中执行: npm install mockjs; 

    第二步:定义index.js文件

    我们新建一个mock文件夹,此文件夹中建一个index.js文件:
    在index.js中输入以下内容:

    import Mock from 'mockjs' //引入mockjs,npm已安装
    import { Random } from 'mockjs' // 引入random对象,随机生成数据的对象,(与占位符@一样)
    Mock.setup({
    timeout:1000 //设置请求延时时间
    })
    const getdata = function(option){ //定义请求数据方法
    let datalist = []
    for (let i = 0; i < 20; i += 1) {
    const o = { //mockjs模拟随机生成数据,生成20条
    recipeId: Random.guid(),
    billId: Random.string(10),
    orgId: Random.string('number', 8, 10),
    Date:Random.date('yyyy-MM-dd'),
    time:Random.time('A HH:mm:ss'),
    adress:Random.county(),
    viewName: Random.cword(4, 16), // 随机生成任意名称
    personName: Random.cname(),
    reason: Random.csentence(10, 32),
    }
    datalist.push(o)
    }
    return{
    data:datalist
    }
    }
    //调用模拟数据方法

    const data = Mock.mock('/user', /post|get/i,getdata)
    const data1 = Mock.mock('/user2', /post|get/i,getdata2)
    export  { data, data1 }


    ---------------------

    方式二:

    const LoginUsers = [
      {
        id: 1,
        username: 'zhangl',
        password: 'qwe123123',
        avatar: '',
        name: 'zhangl'
      }
    ];
    
    const Users = [];
    
    for (let i = 0; i < 50; i++) {
      Users.push(Mock.mock({
        id: Mock.Random.guid(),
        name: Mock.Random.cname(),
        addr: Mock.mock('@county(true)'),
        'age|18-60': 1, // 属性名和属性规则通过|分开
      }));
    }
    
    export { LoginUsers, Users };

    -----------------------
    第三步:在main.js中引入index.js文件:

    import './mock/index' // mock 方式,正式发布时,注释掉该处即可

    第四步:请求数据:

    showdata(){
    this.$http.get('/user') //全局引入使用vue原型中的方法this.$http,已经把axios添加到原型中
    .then((res)=>{
    console.log(res.data.data)
    this.datalist = res.data.data
    })
    .catch((err)=>{
    console.log('调用失败',err)
    })
    }

    ---------------------

  • 相关阅读:
    leetcode--Populating Next Right Pointers in Each Node II
    leetcode—Populating Next Right Pointers in Each Node
    Pascal's Triangle II
    leetcode—pascal triangle
    leetcode—triangle
    October 23rd, 2017 Week 43rd Monday
    October 22nd, 2017 Week 43rd Sunday
    October 21st 2017 Week 42nd Saturday
    October 20th 2017 Week 42nd Friday
    October 19th 2017 Week 42nd Thursday
  • 原文地址:https://www.cnblogs.com/liangjie/p/10646245.html
Copyright © 2011-2022 走看看