版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21262357/article/details/88285621
模拟后台数据请求
cnpm install vue-resource --save
在webpack.dev.conf.js
配置
在const portfinder = require('portfinder')
后面加上以下代码
//请求本地数据
const express = require('express')
const app = express()
const list = require('../static/data/list.json')
const apiRoutes = express.Router()
app.use('/api',apiRoutes)
在devServer
里面添加
before(app) {
app.get('/api/list',(req, res) => {
res.json({
errno: 0,
data: list
})
})
}
运行npm run dev
,在浏览器中打开http://localhost:8080/api/list
,可以看到访问结果
Vue中如何使用axios
cnpm install axios --save
在main.js中插入如下代码:
import axios from 'axios'
Vue.prototype.$axios = axios;
使用一下代码进行调用
this.$axios.get('../static/data/list0.json')
.then((res) => {
console.log(res.data);
}).catch((err) => {
console.log(err);
});
同时请求多个接口
this.$axios
.all([
this.$axios.get('../../static/data/list0.json'),
this.$axios.get('../../static/data/list1.json')
])
.then(
this.$axios.spread(function(list0, list1) {
// 上面两个请求都完成后,才执行这个回调方法
that.list = list0.data;
that.list0 = list0.data;
that.list1 = list1.data;
})
);