mock.js怎么用?

Later

mock.js其实就是把ajax发出去的请求给拦截住,之后返回假数据。

要使用mock首先需要用npm下axios和mockjs

1
npm install axios mockjs

image-20240723233930227

1.建立mock文件夹

image-20240723234402659

2.填入假数据

image-20240723234849417

1
2
3
4
5
6
7
[
{
"msg":"这是假数据1"
},{
"msg":"这是假数据2"
}
]

3.建立service.js

image-20240723235040980

建立假接口,返回假数据:

image-20240723235543902

1
2
3
4
5
6
import Mock from 'mockjs';
import msg from '../index/msg/index.json';

Mock.mock('/mock/getMsg', 'get', {
data: msg
});

4.在main.js里面导入indexService.js

image-20240723235753662

1
2
3
4
5
import { createApp } from 'vue'
import App from './App.vue'
import '@/mock/index/indexService'

createApp(App).mount('#app')

5.调用假接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script setup>
import axios from "axios";
import { reactive } from 'vue';

const msg = reactive({ list: [] });

axios.get('/mock/getMsg')
.then(res => {
msg.list = res.data.data
console.log(res);
});
</script>

<template>
<ul>
<li v-for="(item, index) in msg.list" :key="index">{{ item }}</li>
</ul>
</template>

<style scoped></style>

image-20240724000850082

mock怎么接收数据?

app.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script setup>
import axios from "axios";

const send = () => {
axios.post('/mock/poatSend',{
msg:1
}).then(res => {
console.log(res);
})
};
</script>

<template>
<button @click="send">发送数据</button>
</template>

<style scoped></style>

indexService.js:

1
2
3
4
5
6
7
8
9
import Mock from 'mockjs';

Mock.mock('/mock/poatSend', 'post', (options)=>{
const { msg } = JSON.parse(options.body);

return {
data: "你发送的是:" + msg
};
});

image-20240724002412521

项目下载:点我下载dome

  • 标题: mock.js怎么用?
  • 作者: Later
  • 创建于 : 2024-07-24 00:32:14
  • 更新于 : 2024-07-24 00:33:28
  • 链接: http://www.later0716.top/2024/07/24/mock-js怎么用?/
  • 版权声明: 版权所有 © Later,禁止转载。