Vue - 11.Mock Server 模拟后端数据

1,388 阅读1分钟

通过vue配置文件模拟Mock Server

  1. 在当前根目录新建 vue.config.js,如下结构内容,相当于写一个接口,服务器地址就是当前项目地址localhost:8080,这里的app是后端node.js提供的一个变量对象,相当于call,exprice生成的实例对象,

    module.exports = {
        devServer: {
            before(app, server) {
                //接口,get获取,补全地址为 localhost:8080/api/cartList
                app.get('/api/cartList', (req, res) => {
                    //返回json数据
                    res.json({
                        //返回一个对象,result是对象名,可自定义
                        result: [
                           { id: 1, title: "Vue", price: 188, active: true, count: 1 },
                           { id: 2, title: "Router", price: 288, active: true, count: 1 },
                           { id: 3, title: "Vuex", price: 388, active: false, count: 1 },
                           { id: 4, title: "React", price: 488, active: false, count: 1 }
                        ]
                    })
                })
            }
        }
    }
    

    Mock数据模拟,每次修改完这个文件,一定要重新启动才能生效:npm run serve

  2. 确保cd到项目目录下,终端 npm i axios -S 安装axios

  3. 打开main.js,添加 import Axios from 'axios' 引入axios

  4. main.js的 import下方,添加 Vue.prototype.$http = Axios; ,将axios挂载到vue实例的原型上,每个组件都继承这个实例的原型,所以可以在每个实例中都可以通过 this.$http 拿到 axios 对象

  5. data中声明一个对象用于接收,cartList: [] 通过 created 钩子函数,调用接口获取数据并赋值

    created() {
      this.$http
        .get("api/cartList")
        .then(res => {
          this.cartList = res.data.result;
        })
        .catch(err => {
          console.log(err);
        });
    },
    

    为避免以上这个 Promise 回调地狱的问题,可以用 async - await 语法代替,让异步代码同步化:

    async created() {
      try {
        const res = await this.$http.get("api/cartList");
        this.cartList = res.data.result;
      } catch (error) {
        console.log(error);
      }
    },
    
  6. 在组件中使用数据

Vue Cli devserver配置参考