Vue脚手架系列04-Mock模拟购物车数据

289 阅读1分钟

1.mock模拟购物车数据

1.步骤:

  • 项目文件夹下新建换一个文件-vue.config.js文件,内容如下:
module.exports = {
    devServer:{
        //mock数据模拟,服务器地址就是当前启动项目的服务器地址
        //每次修改完整个config文件,一定要重新启动
        before(app,server){
            //地址 http://localhost:8082/api/cartList
            app.get("/api/cartList",(req,res)=>{
                res.json({
                    result:[
                        {id:1,title:"vue实战开发",price:996,active:true,count:1},
                        {id:2,title:"es6实战开发",price:998,active:true,count:1},
                        {id:3,title:"python实战开发",price:920,active:true,count:1},
                        {id:4,title:"react实战开发",price:123,active:true,count:1},  
                    ]
                })
            })
        }
    }
}
  • 写好vue.config.js,重启后,可以在浏览器通过http://localhost:8082/api/cartList拿到想要的数据。

2.安装axios发送请求

1.安装:

  • 命令行中通过npm i axios --save进行安装

    • 安装完axios后需要在main.js入口文件中,对vue实例挂载axios:

    • 这样就可以在vue的实例中通过this.$http.get/post方法发送请求了

//main.js文件

import Vue from 'vue'
import App from './App.vue'
//导入axios
import axios from "axios";
//这样在vue实例对象中就可以通过this.$http来使用axios了
Vue.prototype.$http = axios;

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
}).$mount('#app')

2.在app.vue发送请求:

  • created生命周期加上async和await,将异步请求同步化
//app.vue文件
<template>
  <div id="app">
    <ul>
      <li v-for="(item,index) in cartList" :key="index">
        <h3>{{item.title}}</h3>
        <p>{{item.price}}</p>
      </li>
    </ul>
    <my-cart :cart="cartList" :title="title"></my-cart>
  </div>
</template>

<script>
import myCart from "./components/Cart";
export default {
  name: 'App',
  components: {
    myCart,
  },
  async created() {
     //🌵简单请求,不用async直接请求
    // this.$http.get("/api/cartList")
    // .then(res=>{
    //   console.log('我是res数据',res);
    //   this.cartList=res.data.result;
    // }).catch(
    //   err=>{
    //     console.log('哇擦嘞!!!报错了',err)
    //   }
    // )
    
    //🌵一般来说都是通过try catch 来解决async 和 await的报错问题
    try {
      const res = await this.$http.get("/api/cartList");
      this.cartList=res.data.result;
    } catch (error) {
      console.log(error);
    }

  },
  data() {
    return {
      cartList:[
        // {id:1,title:"vue实战开发",price:996,active:true,count:1},
        // {id:2,title:"es6实战开发",price:998,active:true,count:1},
        // {id:3,title:"python实战开发",price:920,active:true,count:1},
        // {id:4,title:"react实战开发",price:123,active:true,count:1},        
      ],
      title:"我的购物车"
    }
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
}
</style>

这样mock购物车的数据模拟就完成了,下篇将研究下,如何将数据持久化?

  • 是利用vue的监听机制和localstorage来实现