- 1.下载mock.js和axios
//下载mock.js
npm install mockjs -D
//下载axios
npm install axios
2.在src下创建mock目录,并在mock目录下创建index.js
import { mock } from 'mockjs'; let data = mock({ "data|100": [ //生成100条数据 数组 { "shopId|+1": 1,//生成商品id,自增1 "shopMsg": "@ctitle(10)", //生成商品信息,长度为10个汉字 "shopName": "@cname",//生成商品名 , 都是中国人的名字 "shopTel": /^1(5|3|7|8)[0-9]{9}$/,//生成随机电话号 "shopAddress": "@county(true)", //随机生成地址 "shopStar|1-5": "★", //随机生成1-5个星星 "salesVolume|30-1000": 30, //随机生成商品价格 在30-1000之间 "shopLogo": "@Image('100x40','#c33', '#ffffff','小北鼻')", //生成随机图片,大小/背景色/字体颜色/文字信息 "food|7": [ //每个商品中再随机生成七个food { "foodName": "@cname", //food的名字 "foodPic": "@Image('100x40','#c33', '#ffffff','小可爱')",//生成随机图片,大小/背景色/字体颜色/文字信息 "foodPrice|1-100": 20,//生成1-100的随机数 "aname|14": [ { "aname": "@cname", "aprice|30-60": 20 } ] } ] } ] }); mock(/goods\/goodAll/, 'post', () => { //三个参数。第一个路径,第二个请求方式post/get,第三个回调,返回值 return data })
3.在main中引入mock
import { createApp } from 'vue' import './style.css' import App from './App.vue' import './mock/index.js' ##引入mock,让他全局可用 createApp(App).mount('#app')
4.在App.vue中使用axios请求mock
<template> <div> <button @click="getMessage">获取数据</button> <table border="1" cellspacing='0'> <thead> <tr> <th>销售ID</th> <th>销售描述</th> <th>销售名称</th> <th>电话</th> <th>销售星级</th> <th>卖出数量</th> <th>住址</th> </tr> </thead> <tbody> <tr v-for="item in arr[0]" :key="item.shopId"> <td>{{item.shopId}}</td> <td>{{item.shopMsg}}</td> <td>{{item.shopName}}</td> <td>{{item.shopTel}}</td> <td>{{item.shopStar}}</td> <td>{{item.salesVolume}}</td> <td>{{item.shopAddress}}</td> </tr> </tbody> </table> </div> </template> <script setup> import axios from 'axios' import { reactive } from 'vue'; //赋值给变量 let arr = reactive([]); //获取数据 const getMessage = ()=>{ axios.post("http://localhost:8080/goods/goodAll").then((res)=>{ console.log(res); arr.push(res.data.data); }); } </script> <style scoped> </style>
评论 (0)