mock.js 測試數據(vue + axios)

npm install mockjs
mock01.js
var Mock = require('mockjs');
var data = Mock.mock({
  'users|3-6': [{
    'id|+1': 1,
    'name':'@cfirst@cname',
    'img':()=>Mock.Random.image('80x80', Mock.Random.color(),Mock.Random.province())
  }]
});
console.log(JSON.stringify(data, null, 4))
module.exports =()=>{  return data;  };
json-server mock01.js     //  打開  http://localhost:3000/users
http://localhost:3000/users 展示:
[
  {
    "id": 1,
    "name": "段金軍",
    "img": "http://dummyimage.com/80x80/f279ca&text=浙江省"
  },
  {
    "id": 2,
    "name": "羅姚超",
    "img": "http://dummyimage.com/80x80/79eef2&text=臺灣"
  },
  {
    "id": 3,
    "name": "蘇孫平",
    "img": "http://dummyimage.com/80x80/f2d379&text=廣東省"
  },
  {
    "id": 4,
    "name": "陸賴磊",
    "img": "http://dummyimage.com/80x80/af79f2&text=湖南省"
  }
]

index.html (vue + axios-get

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>cookie_fzx</title>
  <script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
  <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
</head>
<body>
  <div id="app">
    <div v-for="user in users">
      {{ user.id  +  " " +  user.name  }}
      <img   :src="user.img"   alt= "" >
    </div>
  </div>
  
  <script>
    new Vue({
      el:'#app',
      data:{  users: null  },
      mounted() { this.getUserInfo();  },
      methods:{
        getUserInfo(){
          var that = this;
          axios.get('http://localhost:3000/users').then(function (response) {
            console.log(response);
            that.users = response.data;
          })
        }
      }
    })
  </script>
</body>
</html>
index.html 展示:

在這裏插入圖片描述

原理

在這裏插入圖片描述

index.html (vue + axios-post

    <input type="text"   v-model="inputName">
    <button @click="add(inputName)">cookie_fzx</button>

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

data:{  users: null,    inputName: null,  },

    add(inputName){
      var that = this;
      axios({
        method: 'post',
        url: 'http://localhost:3000/users',
        data: {
          name: inputName,
        }
      }).then(function (response) {
        that.getUserInfo();
      });

在這裏插入圖片描述

axios-delete
    axios({
      method: 'delete',
      url: 'http://localhost:3000/users/2',
      data: { }
    }).then(function (response) {
      alert('delete success!')
    });

mock + vuecli

vue create learnmock

cd learnmock

npm install mockjs

scripts/mockdata.js

import Mock from 'mockjs';
const data = Mock.mock({  。。。  });

export default { data }

接下來,在需要用到的mock數據的vue組件頁面中,這樣寫

import mockdata from "@/scripts/mockdata.js";

引用數據,在你methods裏面 直接引用剛剛的mockdata即可。例如:

new Promise((resolve, reject) => {
    that.foods =mockdata.data.foods;  //直接點出你生成的假數據對象即可
    that.foodsListLen = that.foods.length;
 }).catch(err=>{
      console.log(err)
 })

來自!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章