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

说明

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

安装依赖

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

npm i cross-env -D

添加脚本

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

添加支持jsx

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

npm install @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props -D
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, proxyOptions) {
                    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 run serve:no-mock

效果如下:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凯小默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值