资讯详情

Vue·Axios的使用

Vue·Axios的使用

    • 下载引入Axios
    • 引入Axios到项目中
    • 生产与开发环境配置
    • 调用二次封装Axios
    • Axios二次封装
    • Home将使用定义引入页面Axios异步接口与拦截器

·创建浏览器XMLHttpRequests ·从node.js创建http ·支持Promise API ·拦截请求及响应 ·转换请求数据和响应数据 ·取消请求 ·自动转换json数据 ·支持防御的客户端XSRF ·支持浏览器有Chrome、Firefox、Safari、Opera、Edge、IE

官方文档:http://axios-js.com/zh-cn/docs/

下载引入Axios

引入项目根目录

  1. 使用npm引入 npm install axios

  2. 使用bower引入 bower install axios

  3. 使用cdn引入 <script sr="https://unpkg.com/axios/dist/axios.min.js"></script>

在这里插入图片描述

引入Axios到项目中

vue2-manage-v\src\main.js

import Vue from 'vue' import App from './App.vue' //import ElementUI from 'element-ui'; import { 
        Button,Radio,Container,Header,Main,Aside,Menu,Submenu,MenuItem,Dropdown,DropdownMenu,DropdownItem,Row,Card,Col,Table,TableColumn} from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css';  import router from '../router'; import store from '../store'; import http from 'axios';   // 不是插件  Vue.config.productionTip = false  Vue.use( Button ); Vue.use( Radio ); Vue.use( Container ); Vue.use( Main ); Vue.use( Aside ); Vue.use( Header );

Vue.use( Menu );
Vue.use( Submenu );
Vue.use( MenuItem );
Vue.use( Dropdown );
Vue.use( DropdownMenu );
Vue.use( DropdownItem );

Vue.use( Row );
Vue.use( Card );
Vue.use( Col );

Vue.use( Table );
Vue.use( TableColumn );

Vue.prototype.$http = http;  // 绑定属性

new Vue({ 
        
  store,
  router,
  render: h => h(App),
}).$mount('#app')

生产与开发环境配置

位置:vue2-manage-v\config\index.js

export default { 
        
    baseUrl: { 
        
        dev: '/api/',
        pro: ''
    }
}

调用二次封装的Axios

位置:vue2-manage-v\api\data.js

// 接口请求
import axios from './axios'  // ./axios调用自己二次封装的axios

export const getMenu = (param) => { 
        
    return axios.request({ 
        
        url: '/permission/getMenu',
        method: 'post',
        data: param
    })
}

Axios二次封装

位置:vue2-manage-v\api\axios.js

import axios from 'axios';
import config from '../config';

 const baseUrl = process.env.NODE_ENV  == 'development' ? config.baseUrl.dev : config.baseUrl.pro  // 调用开发与生产环境配置
 
console.log('打印配置结果信息为:',baseUrl);


class HttpRequest { 
          // 将axios抽象成工具类

    constructor(baseUrl) { 
        
        this.baseUrl = baseUrl;
    }
    getInsideConfig() { 
        
        const config = { 
        
            baseUrl: this.baseUrl,  // 请求的url信息
            header: { 
        }              // 请求头的信息
        }
        return config
    }

    interceptors(instance) { 
           // 拦截器 
        // 添加请求拦截器
        instance.interceptors.request.use(function (config) { 
        
            // 在发送请求之前做些什么
            return config;
        }, function (error) { 
        
            // 对请求错误做些什么
            return Promise.reject(error);
        });

        // 添加响应拦截器
        instance.interceptors.response.use(function (response) { 
        
            console.log(response, 'response');
            // 对响应数据做点什么
            return response;
        }, function (error) { 
        
            console.log(error, 'error');
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }

    request(options) { 
        
        const instance = axios.create()
        options = { 
         ...this.getInsideConfig(), ...options }  // 对传入的对象进行解构 对axios简单的二次封装
        this.interceptors(instance)                         // 调用拦截器
        console.log('打印:如果控制台显示此信息,表明二次封装成功,否则可能是上面定义的拦截器参数与调用参数不一致,检查参数.');
        return instance(options)
    }
}

export default new HttpRequest(baseUrl)

Home页面引入使用定义的Axios异步接口与拦截器

vue2-manage-v\views\home\index.vue

<template>
    <el-row class="home" :gutter="20">
        <!--//栅格间隔 -->
        <el-col :span="8" style="margin-top: 20px;">
            <el-card shadow="hover">
                <div class="user">
                    <img class="imgp" :src="userImg" />
                    <div class="userinfo">
                        <p class="name" style="float: letf">Admin</p>
                        <p class="access">超级管理员</p>
                    </div>
                </div>
                <p>-------------------------------------------------- </p>
                <div class="login-info">
                    <p style="float: ">上次登陆时间:<span>2021-07-19</span></p>
                    <p>上次登录地点:<span>上海</span></p>
                </div>
            </el-card>
            <el-card>
                <el-table :data="tableData">
                    <el-table-column v-for="(val, key) in tableLabel" :key="key" :prop="key" :label="val">
                    </el-table-column>
                </el-table>
            </el-card>
        </el-col>

        <el-col style="margin-top: 20px" :span="16">
            <!--// 左右两边对齐 -->
            <!--居中text-align: center-->
            <div class="num" style="display: flex;">
                <!--// 浮动 -->
                <el-card v-for="item in countData" :key="item.name" :body-style="{ display: 'flex', padding: 0 }"
                    style=" width: 240px; height: 130px ;text-align: center;">
                    <i class="icon" :calss="`el-icon-${item.icon}`" :style="{ background: item.color }"
                        style=" width: 120px; height: 120px">
                        <div class="detail">
                            <p class="num">¥{ 
        { 
         item.value }}</p>
                            <p class="txt">{ 
        { 
         item.name }}</p>
                        </div>
                    </i>

                </el-card>
            </div>
            <el-card style="height: 280px"></el-card>
            <div class="graph" style=" display: flex;">
                <el-card style="height: 260px;width: 260px;"></el-card>
                <el-card style="height: 260px;width: 260px;"></el-card>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import { 
        getMenu} from '../../api/data.js'

export default { 
        
    name: 'home',
    data() { 
        

        return { 
        
            userImg: require('../../src/assets/images/user.png'),
            tableData: [
                { 
        
                    name: 'oppo',
                    todayBuy: 100,
                    monthBuy: 300,
                    totalBuy: 800
                },
                { 
        
                    name: 'vivo',
                    todayBuy: 100,
                    monthBuy: 300,
                    totalBuy: 800
                },
                { 
        
                    name: '苹果',
                    todayBuy: 100,
                    monthBuy: 300,
                    totalBuy: 800
                },
                { 
        
                    name: '小米',
                    todayBuy: 100,
                    monthBuy: 300,
                    totalBuy: 800
                },
                { 
        
                    name: '三星',
                    todayBuy: 100,
                    monthBuy: 300,
                    totalBuy: 800
                },
                { 
        
                    name: '魅族',
                    todayBuy: 100,
                    monthBuy: 300,
                    totalBuy: 800
                }
            ],
            tableLabel: { 
        
                name: '课程',
                todayBuy: '今日购买',
                monthBuy: '本月购买',
                totalBuy: '总购买'
            },
            countData: [
                { 
        
                    name: "今日支付订单",
                    value: 1234,
                    icon: "success",
                    color: "#ffb980",
                },
                { 
        
                    name: "今日收藏订单",
                    value: 210,
                    icon: "star-on",
                    color: "#2ec7c9",
                },
                { 
        
                    name: "今日未支付订单",
                    value: 1234,
                    icon: "s-goods",
                    color: "#5ab1ef",
                },
                { 
        
                    name: "本月支付订单",
                    value: 1234,
                    icon: "success",
                    color: "#ffb980",
                },
                { 
        
                    name: "本月收藏订单",
                    value: 210,
                    icon: "star-on",
                    color: "#2ec7c9",
                },
                { 
        
                    name: "本月未支付订单",
                    value: 1234,
                    icon: "s-goods",
                    color: "#5ab1ef",
                },
            ]
        }
    },
    mounted() { 
        
        getMenu().then(res => { 
        
            console.log(res)
        })
        // this.$http.get('/user?ID=12345')
        // .then(function (response) { 
        
        // console.log(response);
        // })
        // .catch(function (error) { 
        
        // console.log(error);
        // });
    }  // 生命周期

}
</script>


<style lang="less" scoped>
.home { 
        
    .imgp { 
        
        width: 120px;
        height: 120px;
        border-radius: 50%;
    }
}
</style>



http://localhost:8080/



标签: 5ab反装连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台