天天看点

【Vue 开发实战】实战篇 # 36:如何与服务端进行交互(Axios)

说明

【Vue 开发实战】学习笔记。

安装依赖

windows 需要安装 cross-env 才能拿到参数

npm      

添加脚本

"serve:no-mock": "cross-env MOCK=none vue-cli-service serve"      

添加支持jsx

​​https://github.com/vuejs/jsx-vue2​​

npm install      
module.exports = {
  presets: ["@vue/cli-plugin-babel/preset", "@vue/babel-preset-jsx"],
  "plugins": [
    ["import", { 
      "libraryName": "ant-design-vue",
      "libraryDirectory": "es",
      "style": true // 会加载 less 文件
    }]
  ]
};      

配置 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,) {
                    if (req.headers.accept.indexOf('html') !== -1) {
                        console.log('Skipping proxy for browser request.');
                        return '/index.html';
                    } else if(process.env.MOCK !== "none") {
                        // 将请求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);
                    }
                },
            },
        },
    },
}      

新增一个请求的公共方法

里面使用 jsx 的语法

import axios from "axios";
import { notification } from "ant-design-vue";

function request(options) {
    return axios(options).then(res => {
        return res;
    }).catch((error) => {
        const { response: { status, statusText }} = error;
        notification.error({
            // message: h => (
            //     <div>
            //         请求错误 <span style="color: red">{status}</span>:{options.url}
            //     </div>
            // ),
            message: h => {
                return <div>
                    请求错误 <span style="color: red">{status}</span>:{options.url}
                </div>
            },
            description: statusText
        });
        return Promise.reject(error);
    })
}

export default request;      

在分析页测试不用mock数据

我们使用一个不存在的 api 测试一下 ​

​/api/dashboard/chart1​

<template>
    <div>
        <Chart :option="chartOption" style="width: 600px; height: 400px;"/>
    </div>
</template>

<script>import Chart from "@/components/Chart.vue";
import request from "@/utils/request.js";
export default {
    data() {
        return {
            chartOption: {}
        }
    },
    components: {
        Chart
    },
    mounted() {
        this.getChartData();
        this.interval = setInterval(() => {
            this.getChartData();
        }, 3000);
    },
    beforeDestroy() {
        clearInterval(this.interval);
    },
    methods: {
        getChartData() {
            request({
                url: "/api/dashboard/chart1",
                method: "get",
                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>      

效果如下

启动服务测试一下

npm