创建Mock模拟数据
项目目录下新建文件:vue.config.js
module.exports = {
devServer: {
before(app, server) {
app.get('/api/cartList', (req, res) => {
res.json(
{
result: [
{id:1,title:'Vue实战开发',price:66, avtive:true, count:2},
{id:2,title:'Django实战开发',price:88, avtive:true, count:3},
]
}
)
}
)
}
}
}
使用Mock模拟数据
1.安装请求库:npm i axios -S
2.配置axios
main.js中添加
import axios from "axios";
Vue.prototype.$http = axios;
同步请求
App.vue
export default {
name: 'App',
data(){
return {
cartList : [],
title: "购物车",
}
},
created(){
this.$http.get('/api/cartList')
.then(res=>{
this.cartList = res.data.result
}).catch(error=>{
console.log(error)
})
},
components: {
MyCart
}
}
</script>
异步请求
export default {
name: 'App',
data(){
return {
cartList : [],
title: "购物车",
}
},
async created(){
try {
const res = await this.$http.get('/api/cartList')
this.cartList = res.data.result
}catch(error){
console.log(error)
}
},
components: {
MyCart
}
}
</script>