axios的使用

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

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

安装方法

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

使用 npm:

npm install axios

GET请求

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Vue 测试实例</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="app">
        {{ info }}
    </div>
    <script type="text/javascript">
        new Vue({
            el: '#app',
            data() {
                return {
                    info: null
                }
            },
            mounted() {
                axios
                    .get('https://www.runoob.com/try/ajax/json_demo.json')
                    .then(response => (this.info = response))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            }
        })
    </script>
</body>

</html>

POST请求

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Vue 测试实例</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="app">
        {{ info }}
    </div>
    <script type="text/javascript">
        new Vue({
            el: '#app',
            data() {
                return {
                    info: null
                }
            },
            mounted() {
                axios
                    .post('https://www.runoob.com/try/ajax/demo_axios_post.php')
                    .then(response => (this.info = response))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            }
        })
    </script>
</body>

</html>

post请求form格式

          // 编码类型为application/x-www-form-urlencoded使用
                let form = new URLSearchParams()
                // 编码类型为其他时使用
                // let form = new FormData()
                form.append("pageNum", 1)

                axios
                    .post('地址', form)
                    .then(response => (this.info = response))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });

post请求其他格式

             axios
                    .post('地址', {'pageNum':1})
                    .then(response => (this.info = response))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });

 

posted @ 2021-09-15 21:25  从入门到入土  阅读(884)  评论(0编辑  收藏  举报