数据模拟
使用开发服务器配置vue.config.js中的before选项,可以编写接口,提供模拟数据。
devServer:{
before(app) {
app.get('/api/shiwu', (req, res) => {
setTimeout(() = >{
res.json([{ name: '油条', price: 22}, { name: '玉米', price:33}])
},1000)
})
}
}
接口文件调用:
使用axios需要安装npm i axios -S
src/api/shiwu.js
import axios from 'axios'
export function getShiwu() {
return axios.get('/api/shiwu').then(res => res.data)
}
在vue中引入接口文件
import {getShiwu} from "@/api/shiwu.js"
export default {
data(){
return{
shiwu:""
}
}
async created(){
const shiwu = await getShiwu()
this.shiwu = shiwu
}
}
代理
设置开发服务器代理选项可以有效避免调用接口时出现的跨域问题。
//vue.config.js配置
//如果在本地8080找不到资源,就去3000端口找
devServer: {
proxy