Vue 模板语法 插值操作 绑定属性 计算属性 事件监听 条件判断 循环遍历 阶段案例


发布时间:2021-11-06 17:32:47 作者:有勇气的牛排 阅读(1892) 前端

前言

Vue是一个用于构建用户界面的渐进式框架。与其他大型框架不同的是,Vue被设定为能够由底往上,逐层应用。其不仅语法简单,而且易于与其他第三方项目集成。在单页应用程序上仍能提供强大的支持

1 插值操作

1.1 Mustache语法

也就是双大括号 {{ }}

<div id="app"> <!-- mustche语法中,不仅可以直接写变量,也可以写简单的表达式 --> <h2>{{ message }} : {{ info }}</h2> <h2>{{ message + " : " + info }}</h2> <h2>{{ counter * 2 }}</h2> </div> <script src="../js/vue.js"></script> <script> // 编程范式:声明式编程 const app = new Vue({ el: '#app', // 用于关在要管理的元素 data: { // 定义数据 message: "你好", info: "有勇气的牛排", counter:100 } }) </script>

1.2 v-once

  • 该指令后面不需要跟任何表达式(比如之前的v-for后面是跟表达式的)

  • 该指令表示元素和组件(组件后面才会学习)只会渲染一次,不会随着数据的改变而改变

<div id="app"> <h2>{{ message }}</h2> <h2 v-once>{{ message }}</h2> </div> <script src="../js/vue.js"></script> <script> // 编程范式:声明式编程 const app = new Vue({ el: '#app', // 用于关在要管理的元素 data: { // 定义数据 message: "你好,有勇气的牛排" } }) </script>

1.3 v-html

某些情况下,我们从服务器请求到的数据本身就是一个HTML代码

  • 如果我们直接通过{{ }} 来输出,会将HTML代码也一起输出

  • 但是我们可能希望的是按照HTML格式进行解析,并显示对应的内容

如果我们希望解析出HTML展示

  • 可以使用v-html指令

  • 该指令直面往往会跟上一个string类型

  • 会将string的html解析出来并进行渲染

<div id="app"> <h2>{{ url }}</h2> <h2 v-html="url"></h2> </div> <script src="../js/vue.js"></script> <script> // 编程范式:声明式编程 const app = new Vue({ el: '#app', // 用于关在要管理的元素 data: { // 定义数据 message: "你好,有勇气的牛排", url:'<a href="https://www.couragesteak.com/">开发者</a>' } }) </script>

image.png

1.3 v-text

不推荐,灵活度不够

<div id="app"> <h2 v-text="message"></h2> </div> <script src="../js/vue.js"></script> <script> // 编程范式:声明式编程 const app = new Vue({ el: '#app', // 用于关在要管理的元素 data: { // 定义数据 message: "你好,有勇气的牛排", } }) </script>

1.4 v-pre

v-pre用于跳过这个元素和它子元素的编译过程,用于显示原本的Mustche语法

比如下面代码

  • 第一个h2元素中的内容会被编译解析出来对应的内容

  • 第二个h2元素中会直接显示{{message}}

<div id="app"> <h2>{{ message }}</h2> <h2 v-pre>{{ message }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排" } }) </script>

https://img.couragesteak.com/35c8e45ed7d774541925f8d47a9045aa.png

1.5 v-cloak

在某些情况下,我们浏览器可能会直接显示出未变异的Mustche标签

<div id="app" v-cloak> <h2 v-text="message">{{ message }}</h2> </div>
  • 在vue解析之前,div中有一个属性v-cloak

  • 在vue解析之后,div中没有一个属性v-cloak

2 绑定属性

2.1 v-bind

场景:某些属性需要动态绑定

  • 比如动态绑定a元素的href属性

  • 比如动态绑定img元素的src属性

v-bind指令:

  • 作用:动态绑定属性

  • 缩写::语法糖写法 直接冒号

  • 预期:any(with argument)|Object(without argument)

  • 参数:attrOrProp(optional)

<div id="app">
    <!--    错误做法: 不能在属性中使用mustache语法-->
    <!--    <img src="{{ imgURL }}" alt="">-->

    <!-- 正确做法:使用v-bind指令 -->
    <img v-bind:src="imgURL" alt="">
    <a v-bind:href="aHref">有勇气的牛排</a>

    <!-- 语法糖的写法 -->
    <img :src="imgURL" alt="">
    <a :href="aHref">有勇气的牛排</a>

</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      imgURL: 'https://img.couragesteak.com/4b9785ac56dea2567e62ba08d1ca1767.png',
      aHref: 'https://www.920vip.net/'
    }
  })
</script>

2.2 v-bind绑定class

2.2.1 绑定方式:对象语法

  • 对象语法的含义:class后面跟的是一个对象
<!-- 用法一:直接通过{ }绑定一个类 --> <h2 :class="{'active':isActive}">Hello World</a> <!-- 用法二:也可以通过判断,传入多个值 --> <h2 :class="{'active':isActive,'line':isLine}">Hello World</a> <!-- 用法三:和普通的类同时存在,并不冲突 --> <!-- 注:如果isActive和isLine都为true,那么会有title/active/line三个类 --> <h2 class="title" :class="{'active':isActive,'line':isLine}">Hello World</a> <!-- 用法四:如果过于复杂,可以放在一个methods或者computed中 注:classes是一个计算属性 --> <h2 class="title" :class="classes">Hello World</h2>

2.2.2 绑定方式:数组语法

<div id="app"> <!-- 数组里面的值,加双引号是为值,不加双引号为变量 --> <h2 class="title" :class="[active,line]">{{ message }}</h2> <h2 class="title" :class="getClasses()">{{ message }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排", active: '666', line: '777' }, methods: { getClasses: function () { return [this.active, this.line] } } }) </script>

2.3 点击列表中哪一项,那么该项的文字变为红色

<style> .active { color: red; } </style>
<div id="app"> <ul> <li v-for="(m, index) in movies" :class="{active:index === currentIndex}" @click="liClick(index)" > {{ index }}{{ ' - ' + m }} </li> </ul> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { movies: ['灰太狼', '有勇气的牛排', '导演'], currentIndex: 0 }, methods: { liClick: function (index) { this.currentIndex = index } } }) </script>

2.4 v-bind绑定style

  • 可以使用v-bind:style来绑定一些CSS内敛样式

  • 在写CSS属性名的时候,比如font-size

  1. 我们可以使用驼峰式(cameCase)fontSize

  2. 或短横线分隔(kebab-case,记得用单引号括起来)'font-size'

  • 绑定class有两种方式
  1. 对象语法
<div id="app"> <!-- <h2 :style="key(属性名): value(属性值)">{{ message }}</h2>--> <!-- 50px: 必须加上单引号,否则当做一个变量去解析 --> <h2 :style="{fontSize: '50px'}">{{ message }}</h2> <!-- finalSize当成一个变量使用 --> <h2 :style="{fontSize: finalSize + 'px',color:finalColor}">{{ message }}</h2> <h2 :style="getStyles()">{{ message }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排", finalSize: 60, finalColor: 'red' }, methods:{ getStyles:function () { return {fontSize: this.finalSize + 'px',color:this.finalColor} } } }) </script>
  1. 数组语法
<div id="app"> <h2 :style="[baseStyle, baseStyle1]">{{ message }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排", baseStyle: {backgroundColor: 'red'}, baseStyle1: {fontSize: '100px'} } }) </script>

3 计算属性

  1. 某些情况下,我们可能需要对数据进行一些转换后再显示,或者需要将多个数据结合起来进行显示
  • 比如:有firstName和lastName两个变量,我们需要显示完整的名称。

  • 但是如果多个地方都需要完整的名称,就需要写多个{{ firstName }} {{ laseName }}

  1. 我们可以将上面的代码转换成计算属性

3.1 基本操作

<div id="app"> <h2>{{ name + ' : ' + nameValue }}</h2> <h2>{{ name }} : {{ nameValue }}</h2> <h2>{{ getFullName() }}</h2> <!-- 计算属性 --> <h2>{{ fullName }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { name: "昵称", nameValue: "灰太狼" }, // computed: 计算属性() computed: { fullName() { return this.name + ' : ' + this.nameValue } }, methods: { getFullName() { return this.name + ' : ' + this.nameValue } } }) </script>

3.2 复杂操作

<div id="app"> <h2>总价格: {{ totalProce }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { books: [ {id: 110, name: "C语言", price: 50}, {id: 111, name: "操作系统", price: 60}, {id: 112, name: "统计学习方法", price: 70}, {id: 113, name: "鬼谷子", price: 30}, {id: 114, name: "即兴演讲", price: 35} ] }, computed: { totalProce: function () { let result = 0 for (let i = 0; i < this.books.length; i++) { result += this.books[i].price } return result // for (let i in this.books){ // this.books[i] // } // // for(let book of this.books){ // // } } } }) </script>

3.3 计算属性的setter和getter

<div id="app"> <h2>{{ fullName }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { name: '昵称', nameValue: '有勇气的牛排' }, computed: { // 计算属性一般是没有set方法,只读属性 fullName: { // app.fullName='cc|cc' set: function (newValue) { const names = newValue.split('|'); this.name = names[0]; this.nameValue = names[1]; }, get: function () { return this.name + ' : ' + this.nameValue } }, // 简洁写法 // fullName: function () { // return this.name + ' : ' + this.nameValue // } } }) </script>

3.4 计算属性和methods的对比

<div id="app"> <!-- 1. 直接拼接: 语法过于繁琐 --> <h2>{{ name }} {{ nameValue }}</h2> <!-- 2. 通过定义methods --> <h2>{{ getFullName() }}</h2> <!-- 3. 通过computed --> <h2>{{ fullName }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { name: '昵称', nameValue: '有勇气的牛排' }, computed: { fullName: function () { return this.name + ' : ' + this.nameValue } }, methods: { getFullName: function () { return this.name + ' : ' + this.nameValue } } }) </script>

3.5 计算属性的缓存

计算属性会进行缓存,如果多次使用时,计算属性只会调用一次

4 事件监听

4.1 v-on基本使用

  • 作用:绑定时间监听器

  • 缩写:@

  • 预期:Function | Inline Statement | Object

  • 参数:event

<div id="app"> <!-- v-bind 语法糖 --> <!-- <h2 v-bind:title></h2>--> <!-- <h2 :title></h2>--> <h2>{{ counter }}</h2> <!-- <button v-on:click="counter++">+</button>--> <!-- <button v-on:click="counter--">-</button>--> <!-- button v-on:click="increment">+</button>--> <!-- <button v-on:click="decrement">-</button>--> <!-- v-on 语法糖 --> <button @click="increment">+</button> <button @click="decrement">-</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { counter: 0 }, methods: { increment() { this.counter++ }, decrement() { this.counter-- } } }) </script>

4.2 v-on参数

<div id="app"> <!-- 1. 时间调用的方法没有参数 --> <button @click="btn1Click()">按钮1</button> <button @click="btn1Click">按钮1</button> <br> <!-- 2. 在事件定义时,写函数时省略了小括号,但是方法本身需要一个参数的, 这个时候Vue会默认将浏览器生产的event事件对象作为参数传入到方法 --> <button @click="btn2Click(123)">按钮2</button> <button @click="btn2Click()">按钮2</button> <button @click="btn2Click">按钮2</button> <br> <!-- 3. 方法定义时,我们需要event对象,同时又需要其他参数 --> <!-- 在多用方法时,如何手动的获取到浏览器的event参数对象:$event --> <button @click="btn3Click(123,$event)">按钮3</button> <button>按钮4</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排" }, methods: { btn1Click() { console.log('btn1Click'); }, btn2Click(event) { console.log("按钮2:" + event); console.log(event); }, btn3Click(abc, event) { console.log("按钮3"); console.log(abc, event); } } }) </script>

4.3 v-on修饰符

Vue提供了修饰符来帮助我们方柏霓处理一些事件

  • .stop:调用event.stopPropagation()

  • prevent:调用event.preventDefault()

  • .{keyCode | keyAlias}:只当事件是从特定键触发时才触发回调

  • .native:监听组件根元素的原生事件

  • .once:只触发一次回调

<div id="app"> <!-- 1. .stop修饰符的使用:阻止冒泡 --> <div @click="divClick"> 6666666 <button @click.stop="btnClick">按钮</button> </div> <!-- 2. .prevent修饰符的使用 ->form表单失效 --> <form action="test"> <input type="submit" value="提交" @click.prevent="submitClick"> </form> <!-- 3. 监听某个键盘的键帽 --> <!-- <input type="text" @keyup="keyup">--> <!-- 监听 回车 --> <input type="text" @keyup.enter="keyup"> <!-- 4. .once修饰符的使用 --> <button @click.once="btn2Click">按钮2</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排" }, methods: { btnClick() { console.log("btnClick") }, divClick() { console.log("divClick") }, submitClick() { console.log('submitClick') }, keyup() { console.log('keyup') }, btn2Click() { console.log('btn2Click') } } }) </script>

5 条件判断

5.1 v-if

<div id="app"> <div v-if="isShow"> <div>666</div> </div> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { isShow: true } }) </script>

5.2 v-if v-else

<div id="app"> <div v-if="isShow"> <div>666</div> </div> <div v-else> <div>isShow为false时, 显示我</div> </div> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { isShow: true } }) </script>

5.3 v-if v-else-if v-else

<div id="app"> <h2 v-if="score>=90">优秀</h2> <h2 v-else-if="score>=80">良好</h2> <h2 v-else-if="score>=60">及格</h2> <h2 v-else>不及格</h2> <h1>{{ result }}</h1> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { score: 99, // showMessage:"无" }, computed: { result() { let showMessage = '' if (this.score >= 90) { showMessage = '优秀' } else if (this.score >= 80) { showMessage = '良好' } else if (this.score >= 60) { showMessage = '及格' } else { showMessage = '不及格' } return showMessage } } }) </script>

5.4 用户登录切换的案例(小问题)

<div id="app"> <span v-if="isUserLogin"> <label for="username">用户账号</label><input type="text" id="username" placeholder="用户账号" key="username"> </span> <span v-else> <label for="email">用户邮箱</label><input type="text" id="email" placeholder="用户邮箱" key="email"> </span> <button @click="isUserLogin = !isUserLogin">切换类型</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { isUserLogin: true } }) </script>

5.5 v-show

v-if和v-show对比

  • v-if当条件为false时,压根不会有对应的元素在DOM中。

  • v-show当条件为false时,仅仅是将元素的display属性设置为none而已

开发中国如何选择

  • 当需要在显示与隐藏之间切片很频繁时,使用v-show

  • 当只有一次切换时,通常使用v-if

<div id="app"> <!-- v-if:当条件为false时,包含v-if指令的元素,根本就不会存在dom中--> <h2 v-if="isShow">{{ message }}</h2> <!-- v-show:当 条件为false时,v-show只是给我们的元素添加一个行内样式:display:none --> <h2 v-show="isShow">{{ message }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排", isShow: true } }) </script>

6 循环遍历

6.1 v-for遍历数组

语法格式案例:

# 不需要索引 v-for="movie in movies" # 需要索引 v-for=(item,index) in items
<div id="app"> <!-- 1. 在遍历的过程中,没有使用索引值(下标值) --> <ul> <li v-for="item in names">{{ item }}</li> </ul> <!-- 2. 在遍历的过程中,获取索引值 --> <ul> <li v-for="(item, index) in names"> {{ index + 1 }} - {{ item }} </li> </ul> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { names: ['灰太狼', '有勇气的牛排', '导演'] } }) </script>

6.2 v-for遍历对象

<div id="app"> <!-- 1. 在遍历对象的过程中,如果知识获取一个值,那么获取到的是value --> <ul> <li v-for="item in info">{{ item }}</li> </ul> <!-- 2. 获取index, key和value 格式:(value, key) --> <ul> <li v-for="(value, key) in info">{{ key }} : {{ value }}</li> </ul> <!-- 3. 获取key和value和index 格式:(value, key, index) --> <ul> <li v-for="(value, key, index) in info">{{ index + 1 }}-{{ key }} : {{ value }}</li> </ul> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { info: { name: '灰太狼', age: 18, height: 1.88 } } }) </script>

6.3 使用过程添加key

<div id="app"> <ul> <li v-for="item in letters" :key="item">{{ item }}</li> </ul> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { letters: ['A', 'B', 'C', 'D', 'E'] } }) </script>

6.4 数组方法

<div id="app"> <ul> <li v-for="item in letters" :key="item">{{ item }}</li> <!-- <li v-for="item in letters">{{ item }}</li>--> </ul> <button @click="btnClick">按钮</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { letters: ['A', 'B', 'C', 'D', 'E'] }, methods: { btnClick() { // 1 push方法 // this.letters.push('666','777') // 2 pop() 删除数组中最后一个元素 // this.letters.pop(); // 3 shift() 删除数组中第一个元素 // this.letters.shift(); // 4 unshift() 在数组最前面添加元素 // this.letters.unshift('666', '777'); // 5 splice作用:删除元素/插入元素/替换元素 // 删除元素:第二个参数传入你要删除几个元素(如果没有传,就删除后面所有的元素 // 替换元素:第二个参数,表示我们要替换几个元素,后面是用于替换前面的元素 // 插入元素:第二个参数,传入0,并且后面跟上要插入的元素 // this.letters.splice(1, 0, '1', '2') // 6 sort() // this.letters.sort(); // 7 reverse() this.letters.reverse(); // 修改 // 1非响应式 // 通过索引值修改数组中的元素 // this.letters[0] = '666' // 2响应式 // this.letters.splice(0, 1, '666') // set(要修改的对象, 索引值,修改后的值) Vue.set(this.letters, 0, '666'); } } }) </script>

7 阶段案例

购物车案例:

https://gitee.com/net920vip/vue-framework/tree/master/LearnVuejs01

https://github.com/net920vip/vue-framework/tree/master/LearnVuejs01

8 v-model

  • Vue中使用v-model指令来实现单元数和数据的双向绑定
<input type="text" v-model="message">

等同于

<input type="text" :value="message" @input="message = $event.target.value">

8.1 v-model结合checkbox类型

<div id="app"> <!-- 1 checkbox单选框--> <!-- <label for="protocol">--> <!-- <input type="checkbox" id="protocol" v-model="isAgree">同意协议--> <!-- </label>--> <!-- <h2>您选择的是:{{ isAgree }}</h2>--> <!-- <button :disabled="!isAgree">下一步</button>--> <!-- 2 checkbox多选框--> <label for=""> <input type="checkbox" value="轻音乐" v-model="hobbies">轻音乐 <input type="checkbox" value="国学" v-model="hobbies">国学 <input type="checkbox" value="思考" v-model="hobbies">思考 </label> <h2>您的爱好是:{{ hobbies }}</h2> <label v-for="item in originHobbies"> <input type="checkbox" :value="item" :id="item" v-model="hobbies">{{ item }} </label> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { isAgree: false, // 单选框 hobbies: [], // 多选框 originHobbies: ['国学', '轻音乐', '绘画', '摄影', 'dj', '吉他'] } }) </script>

8.2 v-model结合select类型

<div id="app"> <!-- 1 选择一个 --> <select name="" id="" v-model="hobby"> <option value="国学">国学</option> <option value="轻音乐">轻音乐</option> <option value="绘画">绘画</option> </select> <h2>您的选择是:{{ hobby }}</h2> <!-- 1 选择多个 --> <select name="" id="" v-model="hobbies" multiple> <option value="国学">国学</option> <option value="轻音乐">轻音乐</option> <option value="绘画">绘画</option> </select> <h2>您的选择是:{{ hobbies }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { hobby: "绘画", hobbies:[] } }) </script>

8.3 v-model修饰符

<div id="app"> <!-- 1 修饰符:lazy --> <input type="text" v-model.lazy="message"> <h2>{{ message }}</h2> <!-- 2 修饰符:number --> <input type="number" v-model.number="age"> <h2>{{ age }}---{{ typeof age }}</h2> <!-- 3 修饰符:trim --> <input type="text" v-model.trim="name"> <h2>您输入的名字:{{ name }}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: "你好,有勇气的牛排", age: 0, name: '' } }) </script>

作者:有勇气的牛排(同官网、公众号)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
目录
adfas df
专栏