代理mock数据

2020-01-22  本文已影响0人  回不去的那些时光

1、在根目录新建mock文件夹,然后在文件夹中新建需要的文件名,格式按 模块名_功能名

2、文件中的内容(可以仿照这个来)

// dashboard_chart.js
function chart(method) {
    let res = null;
    switch (method) {
        case 'GET':
            res = [120, 40, 19, 78, 30, 48];
            break;
        default:
            res = null;
    }
    return res;
}

module.exports = chart;

3、vue.config.js(vue的webpack配置文件)

devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true,
            bypass: function (req, res) {
                if (req.headers.accept.indexOf('html') !== -1) {
                    console.log('Skipping proxy for browser request.');
                    return '/index.html';
                } else {
                    const name = req.path.split('/api/')[1].split('/').join('_');
                    const mock = require(`./mock/${name}`);
                    const result = mock(req.method);
                    delete require.cache[require.resolve(`./mock/${name}`)];    // 清除缓存
                    return res.send(result);
                }
            }
        }
    }
}

4、使用

axios
.get("/api/dashboard/chart", {
  params: {
    ID: 12345
  }
})
.then(response => {
  this.chartOption = {
    title: {
      text: "ECharts 入门示例"
    },
    tooltip: {},
    xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {},
    series: [
      {
        name: "销量",
        type: "bar",
        data: response.data
      }
    ]
  };
});
上一篇 下一篇

猜你喜欢

热点阅读