• 【Vue自学笔记(三)】网络请求的简单使用


    如果想要调用接口,需要使用到一个axios,axios必须先导入才可以使用。使用get或post方法即可发送对应的请求,then方法中的回调函数会在请求成功或失败时触发,通过回调函数的形参可以获取响应内容或错误信息。

    本章节只简述简单的使用,详细请见文档:https://github.com/axios/axios

    准备工作

    1. axios库
    <!-- 官网提供的axios在线地址 -->
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    1. 接口

    接口1:随机笑话
    请求地址:https://autumnfish.cn/api/joke/list
    请求方法:get
    请求参数:num(笑话条数,数字)
    响应内容:随机笑话

    接口2:用户注册
    请求地址:https://autumnfish.cn/api/user/reg
    请求方法:post
    请求参数:username(用户名,字符串)
    响应内容:注册成功或失败

    完整代码

    <body>
        <!-- 官网提供的axios库在线地址 -->
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <input type="button" value="get请求" class="get">
        <input type="button" value="post请求" class="post">
    </body>
    <script>
        document.querySelector(".get").onclick = function () {
            axios.get("https://autumnfish.cn/api/joke/list?num=3")
                .then(function (responce) {
                    console.log(responce)
                }, function (err) {
                    console.log(err)
                })
        }
        document.querySelector(".post").onclick = function () {
            axios.post("https://autumnfish.cn/api/user/reg", { username: "天龙教主夫人" })
                .then(function (responce) {
                    console.log(responce)
                }, function (err) {
                    console.log(err)
                })
        }
    </script>
    

    讲解

    querySelector()方法返回文档中匹配指定 CSS 选择器的一个元素。
    注意: querySelector()方法仅仅返回匹配指定选择器的第一个元素。如果你需要返回所有的元素,请使用 querySelectorAll()方法替代。

    get方法对应get请求。参数使用字符串的形式拼接在后面。post方法对应post请求。参数以对象的形式作为参数提供给方法,和url用逗号隔开。

    axios与vue结合

    axios回调函数中的this已经改变无法访问到data中数据,需要把this保存起来,回调函数中直接使用保存的this即可。

    <body>
        <div id="app">
            <input type="button" value="获取笑话" @click="getJoke">
            <P>{{joke}}</P>
        </div>
    </body>
    <script>
        var app = new Vue({
    
            el: "#app",
            data: {
                joke: "很好笑的笑话"
            },
            methods: {
                getJoke: function () {
                    var _this = this
                    axios.get("https://autumnfish.cn/api/joke")
                        .then(function (responce) {
                            _this.joke = responce.data
                            console.log(responce)
                        }, function (err) {
                            console.log(err)
                        })
                }
            }
    
        })
    </script>
    

    很简单,效果就是显示一则笑话。

  • 相关阅读:
    Google Code 项目代码托管网站上 Git 版本控制系统使用简明教程
    C/C++预定义宏
    使用 Raspberry Pi 远程桌面
    Vim 中将 tab 自动转换成空格
    DR模式搭建LVS负载均衡
    NAT模式LVS搭建负载均衡集群
    php扩展memached安装
    raw_input与input的区别
    keepalived+lvs搭建高可用负载均衡集群
    使用keepalived搭建nginx高可用
  • 原文地址:https://www.cnblogs.com/zllk/p/14184725.html
Copyright © 2020-2023  润新知