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)
})