首先,搭建后vue项目框架
1、在public文件夹下准备一个test.json,用来模拟的请求数据
{
"code": 1,
"msg": null,
"data": [
{
"name": "赵一",
"id": 10
},
{
"name": "钱一",
"id": 11
},
{
"name": "孙一",
"id": 12
},
{
"name": "李一",
"id": 13
},
{
"name": "周一",
"id": 14
},
{
"name": "吴一",
"id": 15
},
{
"name": "郑一",
"id": 16
},
{
"name": "王一",
"id": 17
},
{
"name": "陈一",
"id": 18
},
{
"name": "楚一",
"id": 19
},
{
"name": "魏一",
"id": 20
},
{
"name": "吕一",
"id": 21
}
]
}
2、在vue.config.js文件里引入这个文件
const mockData = require('./public/test.json')
module.exports = {
....
devServer: {
open: false,
host: '0.0.0.0',
port: 8080,
https: false,
hotOnly: false,
proxy: {
'/api': {
target: 'http://192.168.0.103:8080',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
},
before: app => {
app.get('/api/test', (req, res) => {
res.json(mockData)
})
}
},
...
}
npm run serve启动项目后运行http://localhost:8080/api/test即可获取请求到的模拟数据
3、在子组件通过axios请求数据
...
<script>
import axios from 'axios';
export default {
....
mounted (){
this.getData();
},
methods: {
getData(){
axios.get('/test').then(res => {
console.log(res);
}).catch(err=>console.log(err))
}
}
....
}
</script>
...