mock.js其实就是把ajax发出去的请求给拦截住,之后返回假数据。
要使用mock首先需要用npm下axios和mockjs
1
| npm install axios mockjs
|
1.建立mock文件夹
2.填入假数据
1 2 3 4 5 6 7
| [ { "msg":"这是假数据1" },{ "msg":"这是假数据2" } ]
|
3.建立service.js
建立假接口,返回假数据:
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
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>
|
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 }; });
|
项目下载:点我下载dome