1.安装mockjs和axios
cnpm install mockjs -S
cnpm install axios -S
目录结构(这里的演示只用到这四个文件)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/769227a3bff77b532d0a70ce63c238ff.png)
2.创建模拟返回的数据(src/mockjs/http.js),放入以下内容
export default {
getData: () => {
return {
code: 200,
tableData: [
{
id: "01",
name: "get测试001",
},
{
id: "02",
name: "get测试002",
},
{
id: "03",
name: "get测试003",
},
{
id: "04",
name: "get测试004",
},
],
};
},
postData: () => {
return {
code: 200,
tableData2: [
{
id: "01",
name: "post测试001",
},
{
id: "02",
name: "post测试002",
},
{
id: "03",
name: "post测试003",
},
{
id: "04",
name: "post测试004",
},
],
};
},
};
3.引入mock,拦截请求,返回模拟的数据(src/mockjs/index.js)放入以下内容
import Mock from "mockjs";
import httpdata from "./http.js";
Mock.mock("/home/getdata", "get", httpdata.getData);
Mock.mock("/home/postdata", "post", httpdata.postData);
4.在全局注册mock(scr/main.js)放入以下内容
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import "./mockjs/index.js";
createApp(App).mount("#app");
5.发送请求测试结果,在(src/App.vue)放入以下内容
<script setup>
import axios from "axios";
import { onMounted } from "vue";
onMounted(() => {
axios.get("/home/getdata").then((res) => {
console.log("get请求返回的数据", res);
});
axios.post("/home/postdata").then((res) => {
console.log("post请求返回的数据", res);
});
});
</script>
<template></template>
<style scoped lang="scss"></style>
6.效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6614f1d67bd66cc3d1b664ebef8172dd.png)