1.目录结构(配置的js文件、要引入json的vue文件、自己编写的json文件)
2.接下来是build/webpack.dev.conf.js文件需要配置的内容
代码:
const express = require('express')
const app = express()
const appData = require('../static/Graphics.json')
const graphicList = appData.contents
const apiRoutes = express.Router()
app.use('/api',apiRoutes)
注意:这里app.get 用的是get请求的。页面请求接口的时候,也需要用get来请求。
代码:
//vue配置请求本地json的数据
before (app) {
app.get('/api/graphicList',(req, res) => {
res.json({
erron:0,
data: graphicList
})//接口返回json数据,上面配置的数据graphicList就赋值给data请求后调用
})
}
3.安装:npm install axios --save-dev
因为页面请求接口要用到axios,所以要先安装,否则页面会报错
4.main.js中导入axios
代码:
import axios from 'axios'; /* 引入axios进行地址访问*/
Vue.prototype.$http = axios;(注意:不使用use来使用该例,而是用prototype原型来使用)
5.接下来就是vue文件的请求写法:
代码:
getGoodsList(){
let _this = this;
axios.get('/api/graphicList').then(function(response){
console.log(response.data.data);
let data = response.data.data;
})
.catch(function(error){
console.log("出错喽:"+error);
});
}