Mockjs is a small, beautiful Mock data artifact
Mockjs
Start with the official address and document address
mockjs
Mockjs document
As described on the official website, it is a data type rich, easy to use, easy to expand the tool.
It makes it easy for us front-end developers to mock data.
A simple example
<script src="http://mockjs.com/dist/mock.js"></script>
<script>
var data = Mock.mock({
The value of the attribute list is an array of 1 to 10 elements
'list|1-10': [{
// Attribute id is an increment, starting at 1 and incrementing by 1 each time
'id|+1': 1}]})console.log(JSON.stringify(data, null.2))
// Output a random array of data from 1 to 10
/ / eg:
/* { list: [ { id:1 }, { id:2 }, { id:3 }, ] } */
</script>
Copy the code
userandom
<script src="http://mockjs.com/dist/mock.js"></script>
<script>
const random = Mock.Random
const friends = ["zgz"."zgz1"."zgz2"]
const data2 = {
email: random.email(),
name: random.cname(),
// Width and height, background color, font color, image format, text
iimage: random.image('200x100'.'#894FC4'.'#FFF'.'debp'.'Mock.js'),
// The same as pick, select an item from friends
firend: random.pick(friends),
city: random.city(),
url: random.url()
}
// Output the result
console.log(JSON.stringify(data2, null.2))
</script>
Copy the code
Mock the GET request and send the request using AXIos
<buttom type="button" id="app">button</buttom>
<script src="http://mockjs.com/dist/mock.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script>
var obj = {
aa:'11'.bb:'22'.cc:'33'.dd:'44'
}
Mock.mock('http://api.yourdomain.com/getlist/'."get", {'user|3-10':[
{
"uid|+1":1.name: '@cname'."age|18-28":0.birthday: '@date("yyyy-MM-dd")'.city: '@city'."fromObj|2": obj
}
]
})
document.querySelector('#app').onclick = function(){
axios.get('http://api.yourdomain.com/getlist/').then(res= >{
// View the output
console.log(res)
}).catch(e= >{
console.log(e)
})
}
</script>
Copy the code
Vue project uses:
// /mock/index.js file (mock total reference file)
const Mock = require('mockjs')
const mocks = require('./mocks')
/* mocks file: //.... module.exports = [ { url:'xxx/' type: 'get/post...', response:()=>{ return { code: 200, data: Total: list.length, list: list}, status: true } } }, { ...do something get / post }, ... ] * /
const mocks = [
...mocks
]
function mockXHR() {
for (const i of mocks) {
// See the official documentation for a similar use of simulated GET requests
Mock.mock(new RegExp(i.url), i.type || 'get', i.response)
}
}
module.exports = {
mocks,
mockXHR
}
Copy the code
// main.js (introduces and initializes the mock interface)
const { mockXHR } = require('./mock')
mockXHR()
Copy the code
// getCourseList sends the Ajax request
import { getCourseList } from '@/api/course'
getCourseList().then(res= > {
console.log(res.list)
});
Copy the code
The end of the
I hope you can point out any mistakes or deficiencies. Thank you for watching.