Vue 基础学习 1.0

Vue基础

网上整理的笔记链接

第一个Vue程序

123

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue基础</title>
</head>

<body>
    <div id="app">
        {{ message }}
    </div>


    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                message: 'Hello Vue!'
            }
        })
    </script>
</body>

</html>

el :挂载点

el是用来设置Vue实例挂载(管理)的元素

Vue实例的作用范围

  • Vue会管理el命中的元素以及其内部的后代元素

是否可以使用其他选择器

  • 可以使用其他选择器,但是建议使用ID选择器

是否可以设置其他dom元素

  • 可以使用其他双标签,不能使用HTMLBODY
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 外部的  {{message}} 被直接渲染到页面里面 -->
    {{message}}

    <!-- 支持各种双标签(不包括body 和html) 单标签不支持   -->
    <div id="app" class="app">
        {{message}}
        <!-- el 命中的元素内部也会被Vue管理 可以任意嵌套其他标签 -->
        <span>{{message}}</span>
    </div>
    
    <h2 id="pp">
        {{message}}
    </h2>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            // 可以使用各种选择器 建议使用id选择器
            // el: "#app",
            // el:'.app',
            el: 'div',
            data: {
                message: "el 挂载点"
            }
        })
        var pp = new Vue({
            el: '#pp',
            data: {
                message: '这里是p标签'
            }
        })
    </script>
</body>

</html>

data:数据对象

  • Vue中用到的数据定义在data中
  • data可以写复杂类型数据
  • 渲染复杂类型数据时,遵守js语法即可
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>data</title>
</head>

<body>
    <div id="app">
        {{ message }}
        <h2>
            {{hero}}
            {{hero.name}}
            {{hero.attack}}
        </h2>
        <ul>
            <li>
                {{game}}
            </li>
            <li>
                {{game[0]}}
            </li>
            <li>
                {{game[1]}}
            </li>
        </ul>
    </div>


    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                message: '游戏',
                hero: {
                    name: '后裔',
                    attack: 'biubiubiu'
                },
                game: ['开心农场', '水果忍者', '愤怒的小鸟']
            }
        })
    </script>
</body>

</html>

本地应用

内容绑定,事件绑定

v-text

  • 设置标签的文本值(textContent)
  • 默认写法会替换全部内容,使用差值表达式{{}}可以替换指定内容
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue基础</title>
</head>

<body>
    <div id="app">
        <p v-text="message + ''"> 这是原来的message</p>
        <p v-text="info ">这是原来的info</p>
        <p >{{message + '!'}} 这是原来的message</p>
    </div>


    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                message: '这是Vue渲染的message',
                info:'这是info'
            }
        })
    </script>
</body>

</html>

v-html

  • v-html指令的作用是,设置元素的innerHTML标签
  • 内容中有html结构会被解析为标签
  • v-text指令无论什么内容是什么,只会解析为文本
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue基础</title>
</head>

<body>
    <div id="app">
        <p v-html='content'></p>
        <p v-text='content'></p>
    </div>


    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                // content:'百度'
                content: '<a href="https://www.baidu.com/">百度</a>'
            }
        })
    </script>
</body>

</html>

v-on

  • v-on指令的作用是为元素绑定事件
  • 事件名不需要写on
  • 智联可以简写为@
  • 方法中的 this 自动绑定为 Vue 实例。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue基础</title>
</head>

<body>
    <div id="app">
         <!-- 绑定了点击事件-->
        <button v-on:click='btn2'>按钮2 </button>
        <!-- 可以用@代替 v-on:这样更简洁 -->
        <button @click='btn1'>按钮1 </button>
        <p @click='kill'>{{hero}} </p>
    </div>


    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                hero: '后裔'
            },
            // methods  被绑定的事件的逻辑写这里
            methods: {
                btn1: function () {
                    alert('按钮1')
                },
                btn2: function () {
                    alert('按钮2')
                },
                kill: function () {
                    this.hero += '单杀'
                    console.log(this);
                }
            }
        })
    </script>
</body>

</html>

v-on补充

事件修饰符地址

https://cn.vuejs.org/v2/api/#v-on

  • 事件绑定的方法写成函数调用的形式,可以传入自定义参数(失效)
  • 定义方法时需要定义形参接收传入的实参(失效)>
  • 从 2.4.0 开始,v-on 同样支持不带参数绑定一个事件/监听器键值对的对象。注意当使用对象语法时,是不支持任何修饰器的。
  • 事件后面跟上.修饰符可以对事件进行限制
  • .enter可以限制触发的按键为回车
  • 事件修饰符有多种

部分修饰符

@keyup.enter 回车按键松开
@keyup.left 左键松开
@keyup.right 右键松开
@keyup.up 上键松开
@keyup.down 下键松开
@keyup.delete 删除键松开

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <!-- 从 2.4.0 开始,v-on 同样支持不带参数绑定一个事件/监听器键值对的对象。注意当使用对象语法时,是不支持任何修饰器的。-->
        <!-- <button @click="doIt(666)">点击</button> -->
        <input type="text" placeholder="这是没有.enter" @keyup='sayHi'>
        <input type="text" placeholder="有.enter"  @keyup.enter='sayHi'>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            methods: {
                doIt:function(p1,p2){
                    console.log(p1);
                    console.log(p2);
                },
                sayHi:function(){
                    alert('你好')
                }
            }
        })
    </script>
</body>

</html>

记事本案例 小总结

  • 创建Vue实例时:el(挂载点),data(数据),methods(方法)
  • v-on指令的作用是绑定事件,简写为@
  • 方法通过this,关键字获取data中的数据
  • v-text指令的作用是:设置元素的文本值,简写为{{}}
  • 数据改变之后,对应元素的显示状态会同步更新
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .app {
            width: 300px;
            height: 100px;
            margin: 100px auto;
        }

        button,
        span {
            width: 50px;
            height: 50px;

        }
    </style>
</head>

<body>
    <div id="app" class="app">
        <button @click='add'>+</button>
        <span>{{num}}</span>
        <button @click='sub'>-</button>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 
        1.data中定义数据 比如num
        2.methods中添加两个方法 add(递增) sub(递减)
        3.使用v-text将num的值赋给span标签
        4.使用v-on将add和sub分别绑定给+和-按钮
        5.累加逻辑:超过10弹出提示 小于0弹出提示
     -->
    <script>
        // 创建vue实例
        var APP = new Vue({
            el: '#app',
            data: {
                num: 1,
            },
            methods: {
                add: function () {
                    if (this.num < 10) {
                        this.num++
                    } else {
                        alert('到边界了')
                    }
                },
                sub: function () {
                    if (this.num > 0) {
                        this.num--
                    } else {
                        alert('到边界了')
                    }
                }
            }
        })
    </script>
</body>

</html>

显示切换,属性绑定

v-show

  • v-show指令的作用是:根据增加切换元素的显示状态
  • 原理是修改元素的display,显示隐藏元素
  • 指令后面的内容,最终会被解析为布尔值
  • 值为true显示元素,值为false隐藏元素
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .yuan {
            width: 100px;
            height: 100px;
            background-color: skyblue;
            border-radius: 50%;
            margin: 100px auto;
        }
        button {
            position: relative;
            left: 0;
            top: 120px;
        }
        .age {
            text-align: center;
            line-height: 100px;
        }
    </style>
</head>
<body>
    <div id="app" class="app">
        <button @click='add'>增加数值</button>
        <button @click='sub'>减少数值</button>
        <button @click='change'>显示和隐藏</button>
        <h2>{{age}}</h2>
        <p>大于17显示小球</p>
        <div v-show='isShow' class="yuan"></div>
        <div v-show='age>=18' class="yuan age"></div>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                isShow: true,
                age: 17
            },
            methods: {
                change: function () {
                    this.isShow = !this.isShow
                },
                add: function () {
                    this.age = this.age + 1
                },
                sub: function () {
                    this.age = this.age - 1
                }
            }

        })
    </script>
</body>

</html>

v-if

  • 和v-show类似
  • v-if指令的作用是:根据表达式的真假切换,来改变元素的显示状态
  • 本质是操纵dom元素来切换显示状态
  • 表达式的值为true,元素存在dom树中,为falsedom树中移除
  • 如果频繁的切换显示和隐藏效果,建议使用v-show(消耗小),反之使用v-if
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <button @click='change'>显示隐藏</button>
        <button @click='addTemperature'>升温</button>
        <button @click='subTemperature'>降温</button>
        <!--
            打开Chrome 开发者工具 
            可以看到v-if指令的的显示和隐藏直接把p删除了
            而v-show只是修改了css的display
         -->
        <p v-if='isShow'>这是v-if</p>
        <p v-show='isShow'>这是v-show</p>

        <p v-if='Temperature > 16'>现在已经{{Temperature}}度了,再降温冷死了</p>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script>
        var app = new Vue({
            el: '#app',
            data: {
                isShow: true,
                Temperature: 20
            },
            methods: {
                change: function () {
                    this.isShow = !this.isShow
                },
                addTemperature: function () {
                    this.Temperature++
                },
                subTemperature: function () {
                    this.Temperature--
                }
            }
        })
    </script>
</body>

</html>

v-bind

  • 操纵元素属性 (比如class src title…)
  • v-bind指令的作用是为:元素绑定属性
  • 完整写法是v-bind:属性名
  • 简写的话可以直接省略v-bind,只保留:属性名
  • 需要动态的增删class建议使用对象的方式
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .active {
        border: 1px solid pink;
    }
</style>

<body>

    <div id="app">
        <!-- 完整写法 -->
        <img v-bind:src="imgSrc" alt="" @click='btn'>
        <br>
        <!-- 简写 -->
        <img :src="imgSrc" alt="" :title="imgTitle">
        <br>
        <!-- class写法  对象方式 建议-->
        <img :src="imgSrc" alt="" :title="imgTitle" :class="{active:isAcive}" @click='changeActive'>
        <br>
        <!-- class的第二种写法 三元表达式  注意里面的单引号-->
        <img :src="imgSrc" alt="" :title="imgTitle" :class="isAcive?'active':''" @click='changeActive'>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                imgSrc: 'http://www.itheima.com/images/logo.png',
                imgTitle: '黑马',
                isAcive: false
            },
            methods: {
                changeActive: function () {
                    this.isAcive = !this.isAcive
                },
                btn: function () {
                    alert(1)
                }
            }
        })
    </script>

</body>

</html>

图片切换案例

  • 列表数据使用数组保存
  • v-bind指令可以设置元素属性,比如src
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .app {
            width: 300px;
            height: 200px;
            /* background-color: pink; */
            margin: 100px auto;
            position: relative;

        }

        .app img {
            width: 300px;
        }

        .app a {
            position: absolute;
            top: 60px;
            color: rgb(255, 255, 255);
            text-decoration: none;
            width: 50px;
            height: 60px;
            background-color: rgba(0, 0, 0, 0.432);
            text-align: center;
            line-height: 60px;
        }

        .left {
            left: 0;
        }

        .right {
            right: 0;
        }
    </style>
</head>

<body>
    <div id="app" class="app">
        <!-- 3.绑定src属性 -->
        <img :src="imgSrc[index]" alt="">
        <a href="javascript:;" class="left" @click='leftClick'></a>
        <a href="javascript:;" class="right" @click='rughtClick'></a>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                // 1.定义图片数组
                imgSrc: [
                    'img/1.jpg',
                    'img/2.jpg',
                    'img/3.jpg',
                    'img/4.jpg'
                ],
                // 2.添加图片索引
                index: 0,
            },
            methods: {
                leftClick: function () {
                    // 4.图片切换逻辑                 
                    if (this.index > 0) {
                        this.index--
                    }
                },
                rughtClick: function () {
                    // 4.图片切换逻辑
                    if (this.index < this.imgSrc.length - 1) {
                        this.index++
                    }
                }
            }

        })
    </script>
</body>

</html>

列表循环,表单元素绑定

v-for

  • v-for指令的作用是:根据数据生成列表结构
  • 数组经常和v-for结合使用
  • 语法时候(item,index)in数据
  • item和index可以结合其他指令一起使用
  • 数组长度的更新会同步到页面上,是响应式的
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <button @click="add">添加</button>
        <button @click="remove">删除</button>
        <ul>
            <!-- index 是索引号 yang 接收来自arr的每一项数据  名字自定义 -->
            <li v-for="(yang,index) in arr">
                {{index +1}} 青青草原: {{yang}}
            </li>
        </ul>
        <!-- 可以和其他指令一起使用 -->
        <h2 v-for="item in lang" v-bind:title="item.name">
            {{item.name}}:
            {{item}}
        </h2>
    </div>

    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                arr: ['喜羊羊', '美羊羊', '沸羊羊', '懒羊羊'],
                lang: [{
                        name: "灰太狼"
                    },
                    {
                        name: "红太狼"
                    }
                ]
            },
            methods: {
                add: function () {
                    this.lang.push({
                        name: "蕉太狼"
                    })
                },
                remove: function () {
                    this.lang.shift();
                }
            }
        })
    </script>
</body>

</html>

v-model

  • v-model指令的作用是便捷的设置和获取表单元素的值(双向数据绑定)
  • 绑定的数据会和表单元素值相关联
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <input type="text" v-model="pkq">
        <p>{{pkq}}</p>
        <button @click="GetP">弹窗</button>
        <button @click="SetP">修改pkq</button>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>    
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                pkq:"皮卡丘"
            },
            methods:{
                GetP:function(){
                    alert(this.pkq)
                },
                SetP:function(){
                    this.pkq = "水箭龟"
                }
            }
        })
    </script>
</body>

</html>

小黑记事本案例

总结分析

  • 列表结构可以通过v-for指令结合数据生成
  • v-on结合事件修饰符可以对事件进行限制,比如.enter
  • v-on在绑定事件时可以传递自定义参数
  • 通过v-model可以快速的设置和获取表单元素的值
  • 基于数据的开发方式
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小黑记事本</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #todoapp {
            width: 700px;
            /* height: 700px; */
            /* background-color: pink; */
            border: 1px solid #ccc;
            margin: 20px auto;
            text-align: center;
            box-shadow: 0px 5px 15px 1px #ccc;
        }

        h1 {
            font-weight: 100;
            font-size: 50px;
            color: #BA5F54;
            margin-bottom: 30px;
            margin-top: 15px;
        }

        .new-todo {
            width: 600px;
            margin-top: 15px;
            color: #666;
            outline-style: none;
            padding: 10px 0;
            font-size: 30px;
            border: 1px solid #ccc;
            text-indent: 20px;
        }

        .new-todo::-webkit-input-placeholder {
            color: #ccc;
            font-size: 30px;
        }

        .main {
            margin: 0 auto;
            width: 600px;
            /* height: 400px; */
            /* background-color: skyblue; */
            border: 1px solid #ccc;
            border-top: none;
            border-bottom: none;
        }

        .main li {
            list-style: none;
            text-align: left;
            border-bottom: 1px solid #ccc;
            font-size: 30px;
            height: 40px;
            color: #ccc;
            padding: 5px 0 5px 60px;
            color: #666;
            position: relative;
        }

        .main li span {
            font-size: 16px;
            position: absolute;
            left: 10px;
            bottom: 10px;
        }

        .main li i {
            position: absolute;
            right: 15px;
            cursor: pointer;
        }


        .footer {
            margin: 0 auto;
            width: 600px;
            height: 50px;
            position: relative;
            border: 1px solid #ccc;
            border-top: none;
            margin-bottom: 40px;
        }

        .footer>div {
            top: 15px;
            position: absolute;
            font-size: 14px;
            color: #666;
        }

        .left {
            left: 10px;
        }

        .right {
            cursor: pointer;
            right: 10px;
        }
    </style>
</head>

<body>
    <!-- 主体区域 -->
    <section id="todoapp">
        <header class="header">
            <h1>小黑记事本</h1>
            <!-- autofocus属性:页面加载时自动获得焦点  -->
            <input v-model="inputValue" @keyup.enter="add" type="text" autofocus autocomplete="off" placeholder="请输入任务"
                class="new-todo">
        </header>
        <!-- 列表区域 -->
        <section class="main">
            <ul>
                <li v-for="(list,index) in list">
                    <span>{{index+1}}</span>
                    {{list}}
                    <i @click="remove(index)">x</i>
                </li>
            </ul>
        </section>
        <!-- 统计和清空 -->
        <footer class="footer">
            <div class="left" v-if='list.length!=0'>{{list.length}} 个</div>
            <div class="right" @click="clear" v-show="list.length!=0">Clear</div>
        </footer>
    </section>
    <!-- 底部 -->
    <footer class="info"></footer>

    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 
        1.新增
            1.1 生成列表结构(v-for 数组)
            1.2 获取用户输入(v-model)
            1.3 回车,新增数据(v-on.enter 添加数据)
            - v-for指令的作用
            - v-model指令的作用
            - v-on指令,事件修饰符
            - 通过审查元素快速定位

        2.删除
            2.1 点击删除指定内容(v-on splice)
            2.2 数据改变。和数据绑定的元素同步改变
            2.3 事件的自定义参数
            2.4 splice的方法的作用
        3.统计
            3.1基于数据的开发方式
            3.2统计信息的个数(v-text length)
        4.清空
            4.1 点击清除所有信息(v-on 清空数组)
        5.隐藏
            5.1 没有数据的时候隐藏底部的统计(-v-show v-if 条件数组非空)
     -->
    <script>
        // 
        var app = new Vue({
            el: "#todoapp",
            data: {
                list: ['星期一', '星期二', '星期三', '星期四'],
                inputValue: ""
            },
            methods: {
                add: function () {
                    this.list.push(this.inputValue)
                },
                remove: function (index) {
                    console.log(index);
                    this.list.splice(index, 1)
                },
                clear: function () {
                    this.list = [];
                }
            }
        })
    </script>
</body>

</html>

网络应用

Vue结合网络数据开发

axios

  • axios必须先导入才可以使用
  • 使用get或者post方法即可发送对应的请求
  • then方法中的回调函数会在请求成功或者失败时候触发
  • 通过回调函数的形参可以获取相应内容,或错误信息

功能强大的网络请求库

官方提供axios在线地址
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axio.get(地址?查询字符串).then(function(response){}).catch(function (error) {});
axio.get(地址?key=value&key2=value2).then(function(response){}).catch(function (error) {});

axio.post(地址,参数对象).then(function(response){}).catch(function (error) {});
axio.post(地址,{key:vlaue,key2:vlaue2}).then(function(response){}).catch(function (error) {});

axios基本使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="get">get请求 </button>
    <button class="post">post请求 </button>

    <!-- 官方提供的 axios在线地址 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        /*
            接口1:随机笑话
            请求地址:https://autumnfish.cn/api/joke/list
            请求方法:get
            请求参数:num(笑话条数,数字)
            响应内容:随机笑话        
        */
        document.querySelector('.get').onclick = function () {
            axios.get("https://autumnfish.cn/api/joke/list?num=4")
                // axios.get("https://autumnfish.cn/api/joke/list123?num=4")
                // 请求成功的时候触发
                .then(function (response) {
                    console.log(response);
                })
                // 请求出错的时候触发
                .catch(function (error) {
                    // console.log(error);
                    console.log('请求失败');
                });
        }
        /*
            接口2:用户注册
            请求地址:https://autumnfish.cn/api/user/reg
            请求方法:post
            请求参数:username(用户名,字符串)
            响应内容:注册成功或失败     
        */
        document.querySelector('.post').addEventListener('click', function () {
            axios.post("https://autumnfish.cn/api/user/reg", {
                    // axios.post("https://autumnfish.cn/api/user123/reg", {
                    username: "啊七"
                })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    // console.log(error);
                    console.log('请求失败');
                });
        })
    </script>
</body>

</html>

axios加Vue

  • axios回调函数中的this已经改变,无法访问到data中的数据
  • 把this保存起来,回调函数直接使用保存的this即可
  • 和本地应用最大的区别就是改变了数据来源
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <button @click="getJoke">获取笑话</button>
        <p>{{joke}}</p>
    </div>

    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 官方提供的 axios在线地址 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script>
        /*
        接口:随机获取一条笑话
        请求地址:https://autumnfish.cn/api/joke/list
        请求方法:get
        请求参数:无
        响应内容:随机笑话
    */
        var APP = new Vue({
            el: "#app",
            data: {
                joke: "这是笑话"
            },
            methods: {
                getJoke: function () {
                    // this发生了改变 所以 将this存在that (38行和43行的输出是不一样的)
                    var that = this
                    console.log(this.joke);
                    axios.get("https://autumnfish.cn/api/joke/list?num=1")
                        .then(function (response) {
                            console.log(response.data.jokes[0]);
                            that.joke = response.data.jokes[0]
                            console.log(this.joke);
                        })
                        .catch(function (err) {

                        })
                }
            }

        })
    </script>
</body>

</html>


posted @ 2020-10-19 21:41  Muliminty  阅读(42)  评论(0)    收藏  举报