说明
【Vue 开发实战】学习笔记。
效果
我们通过 mock 数据来进行开发,比如下面的图表数据来自我们的 mock 数据调用接口 http://localhost:8080/api/dashboard/chart?id=kaimo313
安装依赖
npm install --save axios
编写 mock
新建 ant-design-vue-pro\mock\dashboard_chart.js
文件
let random = require("lodash/random"); function chart(method) { let res = null; switch (method) { case "GET": res = [...new Array(6)].map(() => random(100)); break; default: res = null; } return res; } module.exports = chart;
使用 mock 数据
我们在 ant-design-vue-pro\src\views\Dashboard\Analysis.vue
组件里使用
<template> <div> <Chart :option="chartOption" style="width: 600px; height: 400px;"/> </div> </template> <script> import Chart from "@/components/Chart.vue"; import axios from "axios"; export default { data() { return { chartOption: {} } }, components: { Chart }, mounted() { this.getChartData(); this.interval = setInterval(() => { this.getChartData(); }, 3000); }, beforeDestroy() { clearInterval(this.interval); }, methods: { getChartData() { axios.get("/api/dashboard/chart", { params: { id: "kaimo313" } }).then(response => { this.chartOption = { title: { text: 'ECharts 入门示例' }, tooltip: {}, legend: { data: ['销量'] }, xAxis: { data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] }, yAxis: {}, series: [ { name: '销量', type: 'bar', data: response.data } ] } }) } }, }; </script> <style></style>
vue.config.js 配置
module.exports = { lintOnSave: false, css: { loaderOptions: { less: { javascriptEnabled: true }, } }, devServer: { proxy: { // '@(/api)': { target: 'http://localhost:3000', '/api': { target: 'http://localhost:8080', bypass: function (req, res, proxyOptions) { if (req.headers.accept.indexOf('html') !== -1) { console.log('Skipping proxy for browser request.'); return '/index.html'; } else { // 将请求url转为文件名 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); } }, }, }, }, }
配置参考
https://webpack.docschina.org/configuration/dev-server/#devserverproxy
注意
需要清除缓存,不然每次都是一样的数据,可以看这个状态是否是 304。