Vue 中使用 Axios


Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

先看一个简单示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
        </div>
        <script type="text/javascript" src="../vue.min.js"></script>
        <script src="../node_modules/axios/dist/axios.js"></script>

        <script type="text/javascript">
            var App = {
                template: `
                    <div>
                        <button @click = 'sendAjax'>发请求</button>
                    </div>

                `,
                methods: {
                    sendAjax() {
                        this.$axios.get('http://127.0.0.1:8888/')
                            .then(res => {
                                console.log(res);
                            })
                            .catch(err => {
                                console.log(err);
                            })
                    }
                }

            };

            Vue.prototype.$axios = axios

            new Vue({
                el: '#app',
                template: `<App />`,
                components: {
                    App
                }
            });
        </script>
    </body>
</html>

 

合并请求

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
        </div>
        <script type="text/javascript" src="./vue.min.js"></script>
        <script src="./node_modules/axios/dist/axios.js"></script>

        <script type="text/javascript">
            var App = {
                data() {
                    return {
                        res1: "",
                        res2: ''
                    }
                },
                template: `
                    <div>
                        响应1:{{res1}}
                        响应2:{{res2}}
                        <button @click = 'sendAjax'>合并请求</button>
                    </div>
                `,
                methods: {
                    sendAjax() {
                        // 请求1 get:  /
                        // 请求2 post : /add
                        this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';

                        var q1 = this.$axios.get('');
                        var q2 = this.$axios.post('add', 'a=1');

                        this.$axios.all([q1, q2])
                            .then(this.$axios.spread((res1, res2) => {
                                // 全部成功了
                                this.res1 = res1.data;
                                this.res2 = res2.data;
                            }))
                            .catch(err => {
                                // 其一失败
                                console.log(err);
                            })
                    }
                }
            };

            Vue.prototype.$axios = axios

            new Vue({
                el: '#app',
                template: `<App />`,
                components: {
                    App
                }
            });
        </script>
    </body>
</html>

 

可选项options

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
        </div>
        <script type="text/javascript" src="./vue.min.js"></script>
        <script src="./node_modules/axios/dist/axios.js"></script>
        <script type="text/javascript">
            var App = {
                template: `
                    <div>
                        <button @click = 'sendAjax'>发请求</button>
                    </div>

                `,
                methods: {
                    sendAjax() {

                        this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'
                        this.$axios.get('', {
                                params: {
                                    id: 1
                                },
                                // 在传递给then/catch之前,允许修改响应的数据
                                transformResponse: [function(data) {
                                    // 对 data 进行任意转换处理
                                    // console.log(data);
                                    // console.log(typeof data);
                                    data = JSON.parse(data);
                                    console.log(data);
                                    return data;
                                }]
                            })
                            .then(res => {
                                console.log(res.data.msg);
                            })
                            .catch(err => {
                                console.log(err);
                            })


                        this.$axios.post('/add', {
                                firstName: 'Fred'
                            }, {
                                // `transformRequest` 允许在向服务器发送前,修改请求数据
                                // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
                                // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
                                transformRequest: [function(data) {
                                    // 对 data 进行任意转换处理

                                    console.log(data);

                                    return data;
                                }],

                            })
                            .then(res => {
                                console.log(res);
                            })
                            .catch(err => {
                                console.log(err);
                            })
                    }
                }
            };

            Vue.prototype.$axios = axios

            new Vue({
                el: '#app',
                template: `<App />`,
                components: {
                    App
                }
            });
        </script>
    </body>

</html>

 

一个上传文件的示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
        </div>
        <script type="text/javascript" src="./vue.min.js"></script>
        <script src="./node_modules/axios/dist/axios.js"></script>
        <script type="text/javascript">
            var App = {
                data() {
                    return {
                        file: {},
                        rate: 0
                    }
                },
                template: `
                    <div>   
                        上传进度:{{rate}}%
                        选择文件:
                        <input type="file" name = 'file' @change = 'changeHandler'/>
                        <button @click='sendAjax'>发送请求</button>
                    </div>
                `,
                methods: {
                    sendAjax() {

                        this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';

                        var fd = new FormData();

                        fd.append('file', this.file);
                        this.$axios.post('upload', fd, {

                                onUploadProgress: (progressEvent) => {
                                    // 对原生进度事件的处理
                                    console.log(progressEvent);
                                    var progress = (progressEvent.loaded / progressEvent.total) * 100;
                                    console.log(progress);

                                    this.$nextTick(function() {
                                        this.rate = Math.ceil(progress);
                                    })


                                }
                            })
                            .then(res => {
                                console.log(res);
                            })
                            .catch(err => {
                                console.log(err);
                            })
                    },
                    changeHandler(e) {
                        console.log(e.target.files[0]);
                        this.file = e.target.files[0];
                    }
                }
            };

            Vue.prototype.$axios = axios

            new Vue({
                el: '#app',
                template: `<App />`,
                components: {
                    App
                }
            });
        </script>
    </body>
</html>

 

一个取消请求的示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
        </div>
        <script type="text/javascript" src="./vue.min.js"></script>
        <script src="./node_modules/axios/dist/axios.js"></script>
        <script type="text/javascript">
            var App = {
                data() {
                    return {
                        file: {},
                        rate: 0,
                        source: null,
                        currengtLoaded: 0
                    }
                },
                template: `
                    <div>   
                        上传进度:{{rate}}%
                        选择文件:
                        <input type="file" name = 'file' @change = 'changeHandler'/>
                        <button @click='sendAjax'>发送请求</button>
                        <button @click = 'cancel'>取消请求</button>
                        <button @click = 'resume'>续传</button>
                    </div>
                `,
                methods: {
                    resume() {

                        var fileData = this.file.slice(this.currengtLoaded, this.file.size);

                        var fd = new FormData();

                        fd.append('file', fileData);


                        this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';

                        var CancelToken = this.$axios.CancelToken;

                        var source = CancelToken.source();
                        this.source = source;
                        this.$axios.post('upload', fd, {
                                // 携带取消标识
                                cancelToken: source.token,

                                onUploadProgress: (progressEvent) => {
                                    // 对原生进度事件的处理
                                    console.log(progressEvent);
                                    this.currengtLoaded += progressEvent.loaded;

                                    var progress = (this.currengtLoaded / progressEvent.total) * 100;
                                    console.log(progress);

                                    this.$nextTick(function() {
                                        this.rate = Math.ceil(progress);
                                    })
                                }
                            })
                            .then(res => {
                                console.log(res);
                            })
                            .catch(err => {
                                console.log(err);
                            })
                    },
                    cancel() {
                        this.source.cancel('请求被取消');
                    },
                    sendAjax() {

                        this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';

                        var CancelToken = this.$axios.CancelToken;

                        var source = CancelToken.source();
                        this.source = source;

                        var fd = new FormData();

                        fd.append('file', this.file);
                        this.$axios.post('upload', fd, {
                                // 携带取消标识
                                cancelToken: source.token,

                                onUploadProgress: (progressEvent) => {
                                    // 对原生进度事件的处理
                                    console.log(progressEvent);
                                    this.currengtLoaded = progressEvent.loaded;

                                    var progress = (progressEvent.loaded / progressEvent.total) * 100;
                                    console.log(progress);

                                    this.$nextTick(function() {
                                        this.rate = Math.ceil(progress);
                                    })


                                }
                            })
                            .then(res => {
                                console.log(res);
                            })
                            .catch(err => {
                                console.log(err);
                            })
                    },
                    changeHandler(e) {
                        console.log(e.target.files[0]);
                        this.file = e.target.files[0];
                    }
                }

            };

            Vue.prototype.$axios = axios

            new Vue({
                el: '#app',
                template: `<App />`,
                components: {
                    App
                }
            });
        </script>
    </body>
</html>

 

一个拦截器的示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .spinner {
                margin: 100px auto;
                width: 50px;
                height: 60px;
                text-align: center;
                font-size: 10px;
            }

            .spinner>div {
                background-color: #67CF22;
                height: 100%;
                width: 6px;
                display: inline-block;

                -webkit-animation: stretchdelay 1.2s infinite ease-in-out;
                animation: stretchdelay 1.2s infinite ease-in-out;
            }

            .spinner .rect2 {
                -webkit-animation-delay: -1.1s;
                animation-delay: -1.1s;
            }

            .spinner .rect3 {
                -webkit-animation-delay: -1.0s;
                animation-delay: -1.0s;
            }

            .spinner .rect4 {
                -webkit-animation-delay: -0.9s;
                animation-delay: -0.9s;
            }

            .spinner .rect5 {
                -webkit-animation-delay: -0.8s;
                animation-delay: -0.8s;
            }

            @-webkit-keyframes stretchdelay {

                0%,
                40%,
                100% {
                    -webkit-transform: scaleY(0.4)
                }

                20% {
                    -webkit-transform: scaleY(1.0)
                }
            }

            @keyframes stretchdelay {
                0%,
                40%,
                100% {
                    transform: scaleY(0.4);
                    -webkit-transform: scaleY(0.4);
                }
                20% {
                    transform: scaleY(1.0);
                    -webkit-transform: scaleY(1.0);
                }
            }
        </style>
    </head>

    <body>
        <div id="app">
        </div>
        <script type="text/javascript" src="./vue.min.js"></script>
        <script src="./node_modules/axios/dist/axios.js"></script>
        <script type="text/javascript">
            var App = {
                data() {
                    return {
                        isShow: false
                    }
                },
                template: `
                    <div>
                        <div class="spinner" v-show = 'isShow'>
                          <div class="rect1"></div>
                          <div class="rect2"></div>
                          <div class="rect3"></div>
                          <div class="rect4"></div>
                          <div class="rect5"></div>
                        </div>
                        <button @click = 'sendAjax'>发请求</button>
                    </div>
                `,
                methods: {
                    sendAjax() {
                        // 添加请求拦截器
                        this.$axios.interceptors.request.use((config) => {
                            console.log(config);
                            // 在发送请求之前做些什么
                            var token = localStorage.getItem('token');
                            if (token) {
                                config.headers['token'] = token;
                            }

                            this.isShow = true;
                            return config;
                        }, function(error) {
                            // 对请求错误做些什么
                            return Promise.reject(error);
                        });

                        // 添加响应拦截器
                        this.$axios.interceptors.response.use((response) => {
                            // 对响应数据做点什么
                            console.log(response.data.token);
                            if (response.data.token) {
                                localStorage.setItem('token', response.data.token);
                            }
                            this.isShow = false;
                            return response;
                        }, function(error) {
                            // 对响应错误做点什么
                            return Promise.reject(error);
                        });

                        this.$axios.get('http://127.0.0.1:8888/')
                            .then(res => {
                                console.log(res);
                            })
                            .catch(err => {
                                console.log(err);
                            })
                    }
                }
            };

            Vue.prototype.$axios = axios

            new Vue({
                el: '#app',
                template: `<App />`,
                components: {
                    App
                }
            });
        </script>
    </body>
</html>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM