https://gitee.com/blaunicorn/vue3-vite-mock
F:\code-tencent\vue-study\vue3-mock-demo\vite-project
// vite-project\src\App.vue
<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HelloWorld from "./components/HelloWorld.vue";
import axios from "axios";
import { onMounted, reactive } from "vue";
const state = reactive({
list: [],
});
let getList = () => {
let params = {
// name: 123, //mock 默认是url带参数解析的,
};
axios.get("/api/get/news", { params }).then((res) => {
state.list = res.data;
});
};
let postList = () => {
let data = { id: 1 };
axios.post("/api/post/news", { data }).then((res) => {
state.list = res.data;
});
};
onMounted: {
getList();
}
</script>
<template>
<div>get请求的数据:{{state.list}}</div>
<input
type="button"
value="getList"
@click="getList"
>
<div>post请求的数据:{{state.list}}</div>
<input
type="button"
value="postList"
@click="postList"
>
<img
alt="Vue logo"
src="./assets/logo.png"
/>
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
// vite-project\src\main.js
import { createApp } from 'vue'
import App from './App.vue'
import '../mock/index'
createApp(App).mount('#app')
// vite-project\mock\index.js
import Mock from 'mockjs'
console.log('mock', Mock)
const data = Mock.mock({
// 'string|4': 'test'
string: '@cword(3,8)',
title: '@ctitle',
sentence: '@csentence(50,200)',
content: '@cparagraph', // 随机生成段落
'number|80': 2, // 生辰指定数字
'number|1-999': 1, // 随机生成范围数字
id: '@increment()', // 随机生成增量id
// 生成姓名+身份证号+地址
name: '@cname',
idCard: Mock.Random.id(),
// idCard: '@id(18)',
address: '@city(true)',
guid: Mock.Random.guid(), // 随机uid
// 生成图片:图片大小、图片背景色、图片前景色、图片格式、图片文字
img: '@image("300*250","#ff0000","#fff","gif","@cword")',
// 生成时间
birth: Mock.Random.datetime("yyyy-MM-dd HH:mm:ss"), // 值是指定格式的日期字符串
birth2: new Date(Mock.Random.datetime("yyyy-MM-dd HH:mm:ss")), // 值是 Date 类型
'status|1': ['published', 'draft'], // 随机选择1个
// 数组 指定长度:'data|5' 指定范围'data|5-10'
'list|1-10': [{ name: '@name()', address: '@city', id: '@increment(2)' }]
})
console.log(data)
// mock拦截请求 参数1 url 2 请求类型 3 返回对象或函数
// 设置拦截ajax请求的相应时间
Mock.setup({
timeout: '200-600'
});
Mock.mock('/api/get/news-demo', 'get',
{
code: 200,
message: 'success',
data: data.list
})
// 定义get请求
Mock.mock('/api/get/news', 'get', (config) => {
console.log(config)
return {
code: 200,
message: 'success',
data: data.list
}
})
// 定义post请求
Mock.mock('/api/post/news', 'post', (config) => {
console.log(config)
return {
code: 200,
data: data
}
})