作用:模拟后端数据

创建Mock模拟数据

项目目录下新建文件:vue.config.js

  1. module.exports = {
  2. devServer: {
  3. before(app, server) {
  4. app.get('/api/cartList', (req, res) => {
  5. res.json(
  6. {
  7. result: [
  8. {id:1,title:'Vue实战开发',price:66, avtive:true, count:2},
  9. {id:2,title:'Django实战开发',price:88, avtive:true, count:3},
  10. ]
  11. }
  12. )
  13. }
  14. )
  15. }
  16. }
  17. }

重启项目
image.png

使用Mock模拟数据

1.安装请求库:npm i axios -S
2.配置axios
main.js中添加

  1. import axios from "axios";
  2. Vue.prototype.$http = axios;

同步请求

App.vue

  1. export default {
  2. name: 'App',
  3. data(){
  4. return {
  5. cartList : [],
  6. title: "购物车",
  7. }
  8. },
  9. created(){
  10. this.$http.get('/api/cartList')
  11. .then(res=>{
  12. this.cartList = res.data.result
  13. }).catch(error=>{
  14. console.log(error)
  15. })
  16. },
  17. components: {
  18. MyCart
  19. }
  20. }
  21. </script>

异步请求

  1. export default {
  2. name: 'App',
  3. data(){
  4. return {
  5. cartList : [],
  6. title: "购物车",
  7. }
  8. },
  9. async created(){
  10. try {
  11. const res = await this.$http.get('/api/cartList')
  12. this.cartList = res.data.result
  13. }catch(error){
  14. console.log(error)
  15. }
  16. },
  17. components: {
  18. MyCart
  19. }
  20. }
  21. </script>