1. 程式人生 > 實用技巧 >## 小米路由器mini刷老毛子教程

## 小米路由器mini刷老毛子教程

最近做了一個新的小專案,需要使用mockjs+axios來模擬後臺資料,就來記錄一下mockjs 的使用:

  1. 安裝mockjs和axios

    npm install mockjs --save-dev

    npm install axios --save

  2.在專案裡新建一個mock的資料夾,將mock的請求介面放在此資料夾裡

  

  其中index.js裡面的程式碼如下:

  

// index.js
import Mock from "mockjs";
Mock.mobile_prefix = [
  "134",
  "135",
  "136",
  "137",
  
"138", "139", "150", "151", "152", "157", "158", "159", "130", "131", "132", "155", "156", "133", "153" ]; Mock.bank_prefix = [ "4367", "6227", "6228", "9559", "6222", "9558", "6216", "4563", "6013", "6221", "6210", "6014", "5218", "6282", "3568",
"6226", "4218", "6229", "4864", "6029", "9988" ]; Mock.numeric = "0123456789"; let pagesize = 0; const chartData = () => { // mock隨機資料 const Random = Mock.Random; let dataArr = []; for (let i = 1; i <= pagesize; i++) { let newData = { id: i, user_name: Random.cname(),
// 隨機生成中文姓名 user_bank: Mock.getBank(), // 隨機生成銀行卡卡號(統一19位) phone: Mock.getMobile(), //手機號 status: "已轉賬" }; dataArr.push(newData); } return dataArr; }; Mock.random = (len, list) => { if (len <= 1) { len = 1; } var s = ""; var n = list.length; if (typeof list === "string") { while (len-- > 0) { s += list.charAt(Math.random() * n); } } else if (list instanceof Array) { while (len-- > 0) { s += list[Math.floor(Math.random() * n)]; } } return s; }; Mock.getMobile = () => { return Mock.random(1, Mock.mobile_prefix) + Mock.random(8, Mock.numeric); }; Mock.getBank = () => { return Mock.random(1, Mock.bank_prefix) + Mock.random(15, Mock.numeric); }; // Mock.mock(url,method,data) 三個引數對應 api地址、請求方式、請求引數 Mock.mock("/getData", "post", data => { pagesize = JSON.parse(data.body).pagesize; return { success: "true", code: "200", data: chartData() }; });

3. 將mock/index.js引入到專案裡的main.js中
require("./mock/mock");

  4. 在元件中呼叫介面獲取模擬的資料

  

 let params = { pagesize: this.pagesize };
      let count = this.total % this.pagesize;
      let page = parseInt(this.total / this.pagesize);
      if (this.current > page) {
        params.pagesize = count;
      }
      axios.post("/getData", params).then(res => {
        this.tableData = res.data.data;
      });