vue中 mock使用教程

//mock/index.js
import Mock from 'mockjs' //引入mockjs,npm已安裝
import { Random,toJSONSchema } from 'mockjs' // 引入random對象,隨機生成數據的對象,(與佔位符@同樣)
Mock.setup({
  timeout:1000  //設置請求延時時間
})
const getdata = function(option){ //定義請求數據方法
  let datalist = [];
  var template = {
    'key|1-10': '★'
  }
  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:toJSONSchema(template) ,
      reason: Random.csentence(10, 32),
    }
    datalist.push(o)
  }
  return{
    data:datalist
  }
}

const produceData = function (opt) {
  console.log("opt",opt);
  let articles = [];
  for(let i=0;i<30;i++){
    let newArticleObject = {
      title:Random.csentence(5,30),
      thumbnail_pic_s:Random.dataImage('200x100','Mock.js'),
      author_name:Random.range(10),
      date:Random.date()+''+Random.time(),
      email:Random.email(),
      name:Random.cname()
    }
    articles.push(newArticleObject)
  }
  return {
    data:articles
  }
}
Mock.mock('/name',/post|get/i,produceData)//當post 或者get 請求到news路由時MOCK會攔截請求並返回

Mock.mock('/user', /post|get/i,getdata) //調用模擬數據方法

 

 

相關文章
相關標籤/搜索