Vue学习笔记

1.Vue基础

1.1Vue简介

Vue官网:https://cn.vuejs.org/

官方介绍:

Vue是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库 结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。

Vue特性:

  1. 是一个javaScript框架:必须要遵守一定规则才能使用
  2. 简化Dom操作:Vue会自动操纵由Vue的特殊语法修饰的Dom元素
  3. 响应式数据驱动:页面是由数据来生成的,当数据发生变化时,页面也同步更新

1.2第一个Vue程序

三步骤:

  1. 导入Vue.js
  2. 创建Vue实例对象,设置el和data属性
  3. 第三步:使用简洁的模板语法把数据渲染到页面上{{}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>第一个Vue程序</title>
    <!-- 第一步:导入Vue.js -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        {{message}}<!-- 第三步:使用简洁的模板语法把数据渲染到页面上 {{}}-->
    </div>
    <!-- 第二步:创建Vue实例对象,设置el和data属性 -->
    <script>
        var app = new Vue({
            el:"#app",//指定Dom元素,使用id选择器
            data:{
                message:"Hello Vue!"
            }
        })
    </script>
</body>
</html>

浏览器页面:

1.3el:挂载点

1.3.1思考问题

  1. Vue实例对象的作用范围是什么?
  2. 能否使用其他的选择器,如class选择器、标签选择器?
  3. 能否设置其他的Dom元素?

1.3.2验证问题

1.Vue实例对象的作用范围

我们分别在div标签外、标签内、标签的子标签内使用{{message}}

{{message}}<!--标签外-->
<div id="app">
    {{message}}<!--标签内-->
    <span>{{message}}<!--标签子标签内--></span>
</div>
<!--创建Vue对象-->
<script>
    var app = new Vue({
        el:"#app",//指定div元素
        data:{
            message:"Hello Vue!"
        }
    })
</script>

浏览器页面显示:

结论1:Vue对象只能作用在el属性指定的元素内部

2.能否使用其他的选择器
<!-- 1.id选择器 -->
<div id="app">
    {{message1}}
</div>
<!-- 2.class选择器 -->
<div class="app2">
    {{message2}}
</div>
<!-- 3.标签选择器 -->
<span>{{message3}}</span>

<script>
	//1.id
    var app = new Vue({
        el:"#app",
        data:{
            message1:"id选择器"
        }
    })
    //2.class
    var app2 = new Vue({
        el:".app2",
        data:{
            message2:"class选择器"
        }
    })
    //3.标签
    var app3 = new Vue({
        el:"span",
        data:{
            message3:"标签选择器"
        }
    })
</script>

结论2:可以使用id、class、标签三类选择器。在实际开发中,建议使用id选择器,因为id在一个页面中是唯一的。

3.能否设置其他的Dom元素
<!-- 1.body标签 -->
<body id="app1">
    {{message1}}
    <!-- 2.div标签 -->
    <div id="app2">
        {{message2}}
    </div>
    <!-- 3.h标签 -->
    <h2 id="app3">
        {{message3}}
    </h2>
    <script>
        //1.body
        var app = new Vue({
            el:"#app1",
            data:{
                message1:"body标签"
            }
        })
        //2.div
        var app = new Vue({
            el:"#app2",
            data:{
                message2:"div标签"
            }
        })
        //3.h标签
        var app = new Vue({
            el:"#app3",
            data:{
                message3:"h标签"
            }
        })
    </script>
</body>

浏览器页面:

结论3:只能设置双标签,单标签无法包含{{message}}。不能设置双标签中的html、body、head标签。

1.3.3结论

  1. Vue对象只能作用在el属性指定的元素内部。
  2. 可以使用id、class、标签三类选择器。在实际开发中,建议使用id选择器,因为id在一个页面中是唯一的。
  3. 只能设置双标签,单标签无法包含{{message}}。不能设置双标签中的html、body、head标签。

1.4data:数据对象

data属性也叫数据对象,Vue实例所使用的数据都定义在data属性中。

在前面的第一个Vue程序中,我们只在data属性里定义了一个简单类型:字符串message

但在data中,还可以定义如数组、对象这样的复杂类型:

如何将这样的复杂类型渲染到页面上呢?

实例演示:

<div id="app">
    <!-- 1.简单类型:字符串 -->
    {{message}}
    <!-- 2.复杂类型:对象 -->
    <p>
        失业率:{{school.success}}!
        邮箱:{{school.email}}
    </p>
    <!-- 3.复杂类型:数组 -->
    优秀毕业生:
    <ul>
        <li>{{students[0]}}</li>
        <li>{{students[1]}}</li>
        <li>{{students[2]}}</li>
    </ul>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"家里蹲大学招生啦!",
            school:{
                success:"100%",
                email:"jialidun@qq.com"
            },
            students:["张三","李四","王五"]
        }
    })
</script>

浏览器页面:

2.本地应用

本节目标:

  • 学习常见Vue指令(Vue指令指以v-开头的一组特殊语法命令)
  • 通过Vue实现常见的网页效果

2.1内容、事件绑定指令

2.1.1v-text 设置标签innerText值

语法:

<p v-text="文本内容"></p>
  1. v-text指令可以设置标签内的innerText值
  2. 默认写法会覆盖标签内全部内容。若不想覆盖全部内容,可以使用差值表达式:{{}}替换指定内容
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
    <!-- 1.使用v-text会覆盖标签内原有数据,若不想覆盖,使用{{}} -->
    <h2>{{message}}世界</h2>
    <h2 v-text="message">世界</h2>
    <!-- 2.可拼接字符串 -->
    <h2>{{message + "!"}}</h2>
    <h2 v-text="message + '!'"></h2>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"你好"
        }
    })
</script>

页面显示:

2.1.2v-html设置标签innerHTML值

用法:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
    <!-- 同样,会覆盖标签内数据 -->
    <h2 v-html="message">hello</h2>
    <h2 v-text="message">hello</h2>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"<font style='color:purple'>That's Good</font>"
        }
    })
</script>

页面显示:

2.1.3v-on为元素绑定事件

1.基本语法:

<!-- 完整写法 -->
<button v-on:click="方法名">按钮1</button><br>
<!-- 简略写法:可以将【v-on:】替换为【@】 -->
<button @click="方法名">按钮2</button><br>

2.演示基本用法:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <button v-on:click="fun1">按钮1</button><br>
    <!-- 可以将【v-on:】替换为【@】 -->
    <button @click="fun2">按钮2</button><br>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            food:"炒鸡蛋",
            feel:"好好吃"
        },
        methods:{
            fun1:function(){
                // 可以使用”this.“的方式获取当前data数据对象中的数据
                alert(this.food)
            },
            fun2:function(){
                alert(this.feel)
            }
        }
    })
</script>

页面显示:

3.传递参数

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <button @click="fun('炒鸡蛋真好吃')">按钮</button><br>
    <p v-text="message"></p>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:""
        },
        methods:{
            fun:function(p1){
                this.message = p1;
            }
        }
    })
</script>

4.事件修饰符

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <!--keyup:当按下键盘按钮时触发事件
		.enter:事件修饰符,限制为按下回车键时触发事件
		-->
    <input type="text" @keyup.enter="fun">
</div>
<script>
    var app = new Vue({
        el:"#app",
        methods:{
            fun:function(){
                alert("干饭人,干饭魂!")
            }
        }
    })
</script>

2.1.4计算器案例

目标:

实现:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <div id="app">
        <div class="input-num">
            <button @click="sub">-</button>
            <span>{{num}}</span>
            <button @click="add">+</button>
        </div>
    </div>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                num:1,
                min:0,
                max:10
            },
            methods:{
                // 当大于0时才可以执行减法
                sub:function(){
                    (this.num > 0) ? this.num-- : alert("亲,不能再少了哦!");
                },
                add:function(){
                    (this.num < 10) ? this.num++ : alert("亲,只能买这么多了哦!")
                }
            }
        })
    </script>
</body>
</html>

css样式文件:

body{
  background-color: #f5f5f5;
}
#app {
  width: 480px;
  height: 80px;
  margin: 200px auto;
}
.input-num {
  margin-top:20px;
  height: 100%;
  display: flex;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 4px 4px 4px #adadad;
  border: 1px solid #c7c7c7;
  background-color: #c7c7c7;
}
.input-num button {
  width: 150px;
  height: 100%;
  font-size: 40px;
  color: #ad2a27;
  cursor: pointer;
  border: none;
  outline: none;
  background-color:rgba(0, 0, 0, 0);
}
.input-num span {
  height: 100%;
  font-size: 40px;
  flex: 1;
  text-align: center;
  line-height: 80px;
  font-family:auto;
  background-color: white;
}
img{
  float: right;
  margin-top: 50px;
}

2.2显示切换,属性绑定指令

2.2.1v-show切换元素显示状态

v-show指令的作用是:根据真假切换元素的显示状态

  1. 指令后面的内容,最终都会解析成布尔值
  2. 当值为true时显示元素,为false时隐藏元素

语法:

<img v-show="true/false" src="url">

用法:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <input type="button" value="切换显示隐藏1" @click="switchShow">
    <br>
    <input type="button" value="切换显示隐藏2" @click="addAge">
    <br>
    <!-- 当isShow的值为true时,显示图片;当值为false时,隐藏图片 -->
    <img v-show="isShow" src="https://img0.baidu.com/it/u=212546097,3470597202&fm=26&fmt=auto" width="15%">
    <br>
    <!-- 当age >= 18的值为true时,显示图片;当值为false时,隐藏图片 -->
    <img v-show="age >= 18" src="https://img0.baidu.com/it/u=212546097,3470597202&fm=26&fmt=auto" width="15%">
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            //默认为false
            isShow:false,
            //默认小于18
            age:17
        },
        methods:{
            switchShow:function() {
                //反转isShow的值
                this.isShow = !this.isShow;
            },
            addAge:function() {
                //增加age的值,使得age >= 18 为true
                this.age++;
            }
        }
    })
</script>

页面显示:

v-show切换状态的原理是修改元素的display属性,实现显示/隐藏:

v-show总结:

  1. v-show指令的作用是:根据真假切换元素的显示状态
  2. 原理是修改元素的display属性
  3. 指令后面的内容,最终都会解析为boolean值。
    1. true:元素显示
    2. false:元素隐藏
  4. 数据改变之后,对应元素的显示状态会同步更新

2.2.2v-if切换元素显示状态

v-if指令的作用和v-show一致,都是切换元素的显示状态。

语法:

<p v-if="true/false">内容</p>

用法:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <input type="button" value="切换显示状态1" @click="switchValue">
    <br>
    <input type="button" value="切换显示状态2" @click="addAge">
    <br>
    <!-- 当isFlag的值为true时,显示dom元素;当值为false时,隐藏dom元素 -->
    <p v-if="isFlag">嗯~嗯~嗯 ~啊啊啊啊啊啊~!</p>
    <br>
    <!-- 当age >= 18的值为true时,显示图片;当值为false时,隐藏图片 -->
    <p v-if="age >= 18">FAQ~</p>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            //默认为false
            isFlag:false,
            //默认小于18
            age:17
        },
        methods:{
            switchValue:function() {
                //反转isShow的值
                this.isFlag = !this.isFlag;
            },
            addAge:function() {
                //增加age的值,使得age >= 18 为true
                this.age++;
            }
        }
    })
</script>

页面显示:

v-if的本质是通过操纵dom元素来切换显示状态。

  1. 表达式的值为true,元素存在于dom树中
  2. 表达式的值为false,元素从dom树中移除

该选择哪种切换元素状态命令?

​ 需要频繁的切换时使用v-show,反之使用v-if。前者的切换消耗小。

v-if总结:

  1. v-if指令和v-show指令一样,都是切换元素的显示状态。
  2. v-if的本质是通过操纵dom元素来切换显示状态。
  3. 需要频繁的切换时使用v-show,反之使用v-if。

2.2.3v-bind绑定元素的属性

v-bind指令的作用是:为元素绑定属性

语法:

  • 完整语法是: v-bind:属性名="属性值"
  • 简略写法是::属性名="属性值"

比如img标签中有src、title、class等属性:

<img src="图片地址" >
<img title="这是一张图片">
<img class="active">

使用v-bind命令绑定各个属性:

<div id="app">
    <img v-bind:src= "imgSrc" >
    <img v-bind:title="imgTitle+’!!!!’">
    <img v-bind:class="isActive ? 'active' : '' ">
    <img v-bind:class="{active:isActive}">
</div>

<script>
    var app = new Vue({
        el:"#app",
        data:{
            imgSrc:"图片地址",
            imgTitle:"这是一张图片",
            isActive:false
        }
    })
</script>

简写的话可以直接省略v-bind,只保留 :属性名

<div id="app">
    <img :src= "imgSrc" >
    <img :title="imgTitle+’!!!!’">
    <img :class="isActive ? 'active' : '' ">
    <img :class="{active:isActive}"><!--需要动态的增删class建议使用对象的方式-->
</div>

实例演示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>第一个Vue程序</title>
    <!-- 第一步:导入Vue.js -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <style>
        .active{
            border: 4px solid red;
        }
    </style>
</head>
<body>
    <div id="app">
        <img v-bind:src="imgSrc" v-bind:width="imgSize">
        <img :src="imgSrc" :title="imgTitle + '!!!'" :class="{active:isActive}" :width="imgSize">
        <br>
        <input type="button" @click="addRed" value="添加红框">
    </div>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                imgSrc:"https://img2.baidu.com/it/u=1928705153,984877667&fm=26&fmt=auto",
                imgTitle:"这是一个表情包",
                isActive:false,
                imgSize:"10%"
            },
            methods:{
                addRed:function(){
                    this.isActive = !this.isActive;
                }
            }
        })
    </script>
</body>
</html>

页面显示:

2.2.4图片切换案例

目标:

  1. 点击左右箭头可切换图片
  2. 当切换至首张图片/末尾图片时,隐藏左箭头/右箭头

实现:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>图片切换</title>
  <link rel="stylesheet" href="./css/index.css" />
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <div class="center">
            <!-- 图片 -->
            <!-- 绑定src属性值为imgArr数组里的地址列表,下标为index -->
            <img :src="imgArr[index]"/>
            
            <!-- 左箭头 -->
            <!-- 每次点击左箭头index值减一,当index为0时,隐藏左箭头 -->
            <a href="javascript:void(0)" class="left" @click="prev" v-show="index!=0">
                <img src="./images/prev.png"/>
            </a>
            <!-- 右箭头 -->
            <!-- 每次点击右箭头index值加一,当index大于等于imgArr数组长度时,隐藏右箭头 -->
            <a href="javascript:void(0)" class="right" @click="next" v-show="index < imgArr.length - 1">
                <img src="./images/next.png"/>
            </a>
        </div>
    </div>
  
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                imgArr:[
                    "./images/00.jpg",
                    "./images/01.jpg",
                    "./images/02.jpg",
                    "./images/03.jpg",
                    "./images/04.jpg",
                    "./images/05.jpg",
                    "./images/06.jpg",
                    "./images/07.jpg",
                    "./images/08.jpg",
                    "./images/09.jpg",
                    "./images/10.jpg"
                ],
                index:0
            },
            methods: {
                prev:function() {
                    this.index--;
                },
                next:function() {
                    this.index++;
                }
            }
        })
    </script>
</body>

</html>

css文件:

* {
  margin: 0;
  padding: 0;
}

html,
body,
#app {
  width: 100%;
  height: 100%;
}

#app {
  background-color: #c9c9c9;
  position: relative;
}

#app .center {
  position: absolute;
  background-color: #fff;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
}
#app .center .title {
  position: absolute;
  display: flex;
  align-items: center;
  height: 56px;
  top: -61px;
  left: 0;
  padding: 5px;
  padding-left: 10px;
  padding-bottom: 0;
  color: rgba(175, 47, 47, 0.8);
  font-size: 26px;
  font-weight: normal;
  background-color: white;
  padding-right: 50px;
  z-index: 2;
}
#app .center .title img {
  height: 40px;
  margin-right: 10px;
}

#app .center .title::before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border: 65px solid;
  border-color: transparent transparent white;
  top: -65px;
  right: -65px;
  z-index: 1;
}

#app .center > img {
  display: block;
  width: 700px;
  height: 458px;
}

#app .center a {
  text-decoration: none;
  width: 45px;
  height: 100px;
  position: absolute;
  top: 179px;
  vertical-align: middle;
  opacity: 0.5;
}
#app .center a :hover {
  opacity: 0.8;
}

#app .center .left {
  left: 15px;
  text-align: left;
  padding-right: 10px;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

#app .center .right {
  right: 15px;
  text-align: right;
  padding-left: 10px;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}

2.3列表循环,表单元素绑定指令

2.3.1v-for生成列表结构

v-for指令作用:根据数据生成列表结构。

数组经常和v-for结合使用。

语法:v-for="(item,index) in 数据"

<div id="app">
    <ul>
        <li v-for="(item,index) in arr">
            {{index}}:{{item}}
        </li>
    </ul>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            arr:["张三","李四","王五"],
        }
    })
</script>

生成列表:

数组长度的更新会同步到页面上,是响应式的。

例:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <input type="button" value="增加项" @click="addItem">
    <input type="button" value="减少项" @click="removeItem">
    <!-- 数组 -->
    <!-- 不使用下标 -->
    <ul>
        <li v-for="item in arr">
            {{item}}
        </li>
    </ul>
    <!-- 加入下标 -->
    <ul>
        <li v-for="(item,index) in arr">
            {{index}}:{{item}}
        </li>
    </ul>
    <!-- 对象数组 -->
    <ul>
        <li v-for="(item,index) in objArr">
            {{item.name}}
        </li>
    </ul>
    <ul>
        <li v-for="(item,index) in objArr">
            {{item.email}}
        </li>
    </ul>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            arr:["张三","李四","王五"],
            objArr:[
                {name:"小花",age:21,email:"xiaohua@qq.com"},
                {name:"小华",age:22,email:"xiaohua@qq.com"},
                {name:"小桦",age:23,email:"xiaohua@qq.com"},
            ]
        },
        methods:{
            //添加项
            addItem:function(){
                this.arr.push("赵六");
            },
            //减少项
            removeItem:function(){
                this.arr.shift();
            }
        }
    })
</script>

页面显示:

2.3.2v-model绑定表单元素的值

v-model可以获取表单元素的值并将其与数据对象中的数据绑定起来。

绑定是双向的,当表单元素的值改变时,数据对象中的数据也随之更新,反之亦然。

基本语法:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <!--将文本框的值与message绑定-->
    <input type="text" v-model="message"/>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"芜湖"
        }
    })
</script>

演示双向绑定效果:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
    <input type="text" v-model="message"/>
    <br>
    <button @click="setMessage('重置')">设置message</button>
    <h2>{{message}}</h2>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"芜湖"
        },
        methods:{
            setMessage:function(p1) {
                this.message = p1;
            }
        }
    })
</script>

2.3.3案例:小黑记事本

<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <title>小黑记事本</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <meta name="robots" content="noindex, nofollow" />
  <meta name="googlebot" content="noindex, nofollow" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" type="text/css" href="./css/index.css" />
</head>

<body>
  <!-- 主体区域 -->
  <section id="todoapp">
    <!-- 输入框 -->
    <header class="header">
      <h1>小黑记事本</h1>
      <input v-model="inputValue" @keyup.enter="add" autofocus="autofocus" autocomplete="off" placeholder="请输入任务"
        class="new-todo" />
    </header>
    <!-- 列表区域 -->
    <section class="main">
      <ul class="todo-list">
        <li class="todo" v-for="(item,index) in list">
          <div class="view">
            <span class="index">{{ index+1 }}.</span>
            <label>{{ item }}</label>
            <button class="destroy" @click="remove(index)"></button>
          </div>
        </li>
      </ul>
    </section>
    <!-- 统计和清空 -->
    <footer class="footer" v-show="list.length!=0">
      <span class="todo-count" v-if="list.length!=0">
        <strong>{{ list.length }}</strong> items left
      </span>
      <button v-show="list.length!=0" class="clear-completed" @click="clear">
        Clear
      </button>
    </footer>
  </section>
  
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    var app = new Vue({
      el: "#todoapp",
      data: {
        list: ["写代码", "吃饭饭", "睡觉觉"],
        inputValue: "好好学习,天天向上"
      },
      methods: {
        add: function () {
          this.list.push(this.inputValue);
        },
        remove: function (index) {
          console.log("删除");
          console.log(index);
          this.list.splice(index, 1);
        },
        clear: function () {
          this.list = [];
        }
      },
    })
  </script>
</body>

</html>

3.网络应用

本节主要讲的是Vue结合网络数据的开发应用

3.1axios网络请求库

3.1.1axios简介

axios是一个功能强大的网络请求库,内部是封装的ajax。

由于功能单一,就是发送请求,所以容量很小。并且可以非常方便地和其他框架或者库结合使用,比如说vue。

官方文档:https://github.com/axios/axios

3.1.2axios基本使用

使用前需要引入axios

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

引入页面后,就在当前页面注册了一个全局的axios对象,通过它就可以发送axios请求了。

请求方式有两种:

1.get请求

<script>
	axios.get("服务地址?key1=value1&key2=value2").then(function(response){},function(err){})
</script>

其中,第一个形参为response的回调函数会在请求成功时触发,第二个形参为err的回调函数会在请求失败时触发

2.post请求

post请求和get请求大体一致,只不过请求参数是以对象的形式写在post方法的第二个参数中。

<script>
	axios.post("服务地址",{key1:value1,key2:value2}).then(function(response){},function(err){})
</script>

实例演示:

1.get请求:

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

<input type="button" value="get请求" onclick="joke()"><br>
<script>
    /*
        接口1:随机笑话
        请求地址:https://autumnfish.cn/api/joke/list
        请求方法:get
        请求参数:num(笑话条数,数字)
        响应内容:随机笑话
    */
    var joke = function() {
        axios.get("https://autumnfish.cn/api/joke/list?num=3").then(
            function(response){
                // alert(response)
                console.log(response);
            },
            function(err){
                console.log(err);
            }
        )
    }
</script>

请求成功:

请求失败:修改为错误的地址,重新发送get请求

查看发送的请求:全部都是ajax

2.post请求

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

<input type="button" value="post请求" onclick="regist()"><br>

<script>
    /*
         接口2:用户注册
         请求地址:https://autumnfish.cn/api/user/reg
         请求方法:post
         请求参数:username(用户名,字符串)
         响应内容:注册成功或失败
     */
    var regist = function(){
        axios.post("https://autumnfish.cn/api/user/reg",{username:"Fucker"}).then(
            function(response){
                console.log(response);
            },
            function(err){
                console.log(err);
            }
        )
    }
</script>

发送请求成功:

3.2axios结合vue

vue通过数据对象将数据设置到dom元素上,若想改变数据,需要在方法内使用this.数据获取并设置数据对象中的数据。

但是在axios的回调函数里使用this.数据获取的还是数据对象中的数据吗?

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

<div id="app">
    <input type="button" value="点击获取笑话" @click="getJoke"/><br>
    <p>{{joke}}</p>
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            joke:"一条笑话"
        },
        methods:{
            /*
                接口:随机获取一条笑话
                请求地址:https://autumnfish.cn/api/joke
                请求方法:get
                请求参数:无
                响应内容:随机笑话
            */
            getJoke:function() {
                console.log("回调函数外:" + this.joke);
                axios.get("https://autumnfish.cn/api/joke").then(
                    function(response) {
                        console.log("回调函数内:" + this.joke);
                    }
                )
            }
        }
    })
</script>

结果:

可见,axios回调函数外的this和回调函数内的this指定的对象不一致,前者指定vue的数据对象,后者指定axios对象。

为了将axios获取的数据赋给vue的数据对象,可以在回调函数外先将this指代的vue数据对象赋给一个变量,在回调函数内将获取到的数据赋给该变量即可

<script>
    var app = new Vue({
        el:"#app",
        data:{
            joke:"一条笑话"
        },
        methods:{
            getJoke:function() {
                //定义变量that,将this指代的vue数据对象赋给that
                var that = this;
                axios.get("https://autumnfish.cn/api/joke").then(
                    function(response) {
                        //将axios请求到的数据赋给that指代的vue数据对象
                        that.joke = response.data;
                    },
                    function(err){
                        console.log(err);
                    }
                )
            }
        }
    })
</script>

页面显示:

posted @ 2021-11-05 20:13  TSCCG  阅读(382)  评论(0编辑  收藏  举报