Vue项目加载本地的json数据模拟请求后台数据

1. 安装express和axios

npm i express --save &  npm i axios --save 

网速不好的,可以安装淘宝镜像,使用cnpm

2. 在main.js中引入axios,并挂载到全局

import axios from ‘axios’;

Vue.prototype.$axios = axios;

3.在项目中static(静态资源)中,新建一个存储本地JSON数据

4. 在build/webpack.dev.conf.js中配置express并设置路由规则

// 增加express start
const express = require('express');
const app = express();
const appData = require('../static/json/appData.json'); //导入本地的json数据
const runRedLight = appData.runRedLight;
const redLightRoad = appData.redLightRoad;
const apiRoutes = express.Router();
app.use('/api',apiRoutes);
// 增加express end
5.在build/dev-server.js中添加路由规则

//express start
before(app){
app.get('/api/light',(reg,res)=>{
res.json({
errno:0,
data:runRedLight
})
}),
app.get('/api/road',(reg,res)=>{
res.json({
errno:0,
data:redLightRoad
})
})
}
//express end
6.最后在各组件(xxx.vue)中使用了

created(){
  this.getLocalData()
})
}
methods:{
 getLocalData() {
this.$axios.get('/api/light').then(res=>{
console.log(res.data);
}
}

猜你喜欢

转载自www.cnblogs.com/freyfeng/p/9908309.html