天天看點

【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