Vue 指令、计算属性、侦听器

目录

指令

指令修饰符

按键修饰符

​编辑

v-model修饰符

事件修饰符

v-bind对于样式操作的增强

操作class

对象

数组

操作style

v-model应用于其他表单元素

computed计算属性

概念

基础语法

​编辑

计算属性vs方法

computed计算属性

作用

语法

缓存特性

methods方法

作用

语法

​编辑

完整写法

​编辑

watch侦听器

基础语法

完整写法


指令

指令修饰符

通过"."指明一些指令的后缀,不同后缀封装了不同的处理操作,能够简化代码

按键修饰符

    @keyup.enter  键盘回车监听

<!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>019指令修饰符</title>
</head>
<body><div id="app"><h3>@keyup.enter 监听键盘回车事件</h3><input @keyup.enter="fn" v-model="username" type="text"></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {username: ''},methods: {fn (e) {// if (e.key === 'Enter') {//   console.log('键盘回车的时候触发', this.username)// }console.log('键盘回车的时候触发', this.username)}}})</script>
</body>
</html>

v-model修饰符

    v-model.trim  去除首尾空格

    v-model.number  转数字

事件修饰符

    @事件名.stop  阻止冒泡

    @事件名.prevent  阻止默认行为

<!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>020指令修饰符事件修饰符和v-model修饰符</title><style>.pink {width: 200px;height: 200px;background-color: pink;margin-top: 20px;}.blue {width: 100px;height: 100px;background-color: skyblue;}</style>
</head>
<body><div id="app"><h3>v-model修饰符.trim.number</h3>姓名:<input v-model.trim="username" type="text"><br>年纪:<input v-model.number="age" type="text"><br><h3>@事件名.stop 阻止冒泡</h3><div @click="pinkFn" class="pink"><div @click.stop="blueFn" class="blue">blue</div></div><h3>@事件名.prevent 阻止默认行为</h3><a @click.prevent href="http://www.baidu.com">阻止默认行为</a></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {username: '',age: '',},methods: {pinkFn () {alert('pink被点击了')},blueFn (e) {// e.stopPropagation()alert('blue被点击了')}}})</script>
</body>
</html>

v-bind对于样式操作的增强

为了方便开发者进行样式控制,Vue扩展了v-bind的语法,可以针对class类名style行内样式进行控制

操作class

语法:class="对象/数组"

对象

键就是类名,值是布尔值。如果值为true,有这个类,否则没有这个类

<div class="box"  :class="{ 类名1: 布尔值, 类名2: 布尔值}"></div>

适用场景:一个类名来回切换

数组

数组中所有类,都会添加到盒子上,本质就是一个class列表

<div class="box"  :class="[类名1, 类名2,类名3]"></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>021v-bind对于样式class的控制</title><style>.box {width: 200px;height: 200px;border: 3px solid #000;font-size: 30px;margin-top: 10px;}.pink {background-color: pink;}.big {width: 300px;height: 300px;}</style>
</head>
<body><div id="app"><div class="box" :class="{ pink: true, big: true }">Vue</div><div class="box" :class="['pink', 'big']">Vue</div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {}})</script>
</body>
</html>

操作style

语法:style="样式对象"

<div class="box"  :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值}"></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>022v-bind对于样式style的控制</title><style>.box {width: 200px;height: 200px;background-color: rgb(187, 150, 156);}</style>
</head>
<body><div id="app"><div class="box" :style="{ width: '400px', height: '400px', backgroundColor: 'green' }"></div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {}})</script>
</body>
</html>

v-model应用于其他表单元素

常见的表单元素都可以用v-model绑定关联,以快速获取设置表单元素的值

它会根据控件类型自动选取正确的方法来更新元素

  • 输入框 input:text   value
  • 文本域 input:text   value
  • 复选框 input:checkbox    checked
  • 下拉菜单select    value
  • ......
<!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>023v-model应用于其他表单元素</title><style>textarea {display: block;width: 240px;height: 100px;margin: 10px 0;}</style>
</head>
<body><div id="app"><h3>个人信息</h3>姓名:<input type="text" v-model="username"> <br><br>是否单身:<input type="checkbox" v-model="isSingle"> <br><br><!-- 前置理解:1. name:  给单选框加上 name 属性 可以分组 → 同一组互相会互斥2. value: 给单选框加上 value 属性,用于提交给后台的数据结合 Vue 使用 → v-model-->性别: <input v-model="gender" type="radio" name="gender" value="1">男<input v-model="gender" type="radio" name="gender" value="2">女<br><br><!-- 前置理解:1. option 需要设置 value 值,提交给后台2. select 的 value 值,关联了选中的 option 的 value 值结合 Vue 使用 → v-model-->所在城市:<select v-model="cityId"><option value="101">北京</option><option value="102">上海</option><option value="103">成都</option><option value="104">南京</option></select><br><br>自我描述:<textarea v-model="desc"></textarea> <button>立即注册</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {username: '',isSingle: false,gender: "2",cityId: '102',desc: ""}})</script>
</body>
</html>

computed计算属性

概念

基于现有的数据,计算出来的新属性。依赖的数据变化,自动重新计算

基础语法

  1. 声明再computed配置项中,一个计算属性对应一个函数
  2. 使用起来和普通属性一样使用{{计算属性名}}
<!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>024计算属性</title><style>table {border: 1px solid #000;text-align: center;width: 240px;}th,td {border: 1px solid #000;}h3 {position: relative;}</style>
</head>
<body><div id="app"><h3>物品清单</h3><table><tr><th>名字</th><th>数量</th></tr><tr v-for="(item, index) in list" :key="item.id"><td>{{ item.name }}</td><td>{{ item.num }}个</td></tr></table><!-- 目标:统计求和,求得物品总数 --><p>物品总数:{{ totalCount }} 个</p></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {// 现有的数据list: [{ id: 1, name: '篮球', num: 1 },{ id: 2, name: '玩具', num: 2 },{ id: 3, name: '铅笔', num: 5 },]},computed: {totalCount () {// 基于现有的数据,编写求值逻辑// 计算属性函数内部,可以直接通过 this 访问到 app 实例// console.log(this.list)// 需求:对 this.list 数组里面的 num 进行求和 → reducelet total = this.list.reduce((sum, item) => sum + item.num, 0)return total}}})</script>
</body>
</html>

计算属性vs方法

computed计算属性

作用

封装了一段对于数据的处理,求得一个结果

语法
  1. 写在computed配置项中
  2. 作为属性直接使用,this.计算属性{{计算属性}}
缓存特性

计算属性会对计算出来的结果缓存,再次使用直接读取缓存,依赖项变化了,会自动重新计算,并再次缓存

methods方法

作用

给实例提供一个方法,调用以处理业务逻辑

语法
  1. 写在methods配置项中
  2. 作为方法,需要调用 this.方法名(){{方法名()}}  @事件名="方法名"
<!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><style>table {border: 1px solid #000;text-align: center;width: 300px;}th,td {border: 1px solid #000;}h3 {position: relative;}span {position: absolute;left: 145px;top: -4px;width: 16px;height: 16px;color: white;font-size: 12px;text-align: center;border-radius: 50%;background-color: #e63f32;}</style>
</head>
<body><div id="app"><h3>物品清单🛒<span>{{ totalCountFn() }}</span></h3><h3>物品清单🛒<span>{{ totalCountFn() }}</span></h3><h3>物品清单🛒<span>{{ totalCountFn() }}</span></h3><h3>物品清单🛒<span>{{ totalCountFn() }}</span></h3><table><tr><th>名字</th><th>数量</th></tr><tr v-for="(item, index) in list" :key="item.id"><td>{{ item.name }}</td><td>{{ item.num }}个</td></tr></table><p>物品总数:{{ totalCountFn() }} 个</p></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {// 现有的数据list: [{ id: 1, name: '篮球', num: 3 },{ id: 2, name: '玩具', num: 2 },{ id: 3, name: '铅笔', num: 5 },]},methods: {totalCountFn () {console.log('methods方法执行了')let total = this.list.reduce((sum, item) => sum + item.num, 0)return total}},computed: {// 计算属性:有缓存的,一旦计算出来结果,就会立刻缓存// 下一次读取 → 直接读缓存就行 → 性能特别高// totalCount () {//   console.log('计算属性执行了')//   let total = this.list.reduce((sum, item) => sum + item.num, 0)//   return total// }}})</script>
</body>
</html>

完整写法

计算属性默认的简写,只能读取访问,不能修改

如果需要修改,要写计算属性的完整写法

<!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>026计算属性完整写法</title><style>input {width: 30px;}</style>
</head>
<body><div id="app">姓:<input type="text" v-model="firstName"> +名:<input type="text" v-model="lastName"> =<span>{{ fullName }}</span><br><br><button @click="changeName">改名</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {firstName: '刘',lastName: '备',},methods: {changeName () {this.fullName = '黄忠'}},computed: {// 简写 → 获取,没有配置设置的逻辑// fullName () {//   return this.firstName + this.lastName// }// 完整写法 → 获取 + 设置fullName: {// (1) 当fullName计算属性,被获取求值时,执行get(有缓存,优先读缓存)//     会将返回值作为,求值的结果get () {return this.firstName + this.lastName},// (2) 当fullName计算属性,被修改赋值时,执行set//     修改的值,传递给set方法的形参set (value) {// console.log(value.slice(0, 1))          // console.log(value.slice(1))         this.firstName = value.slice(0, 1)this.lastName = value.slice(1)}}}})</script>
</body>
</html>

watch侦听器

作用:监视数据变化,执行一些业务逻辑或异步操作

基础语法

简单类型数据,直接监视

<!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>026watch侦听器简单写法</title><style>* {margin: 0;padding: 0;box-sizing: border-box;font-size: 18px;}#app {padding: 10px 20px;}.query {margin: 10px 0;}.box {display: flex;}textarea {width: 300px;height: 160px;font-size: 18px;border: 1px solid #dedede;outline: none;resize: none;padding: 10px;}textarea:hover {border: 1px solid #1589f5;}.transbox {width: 300px;height: 160px;background-color: #f0f0f0;padding: 10px;border: none;}.tip-box {width: 300px;height: 25px;line-height: 25px;display: flex;}.tip-box span {flex: 1;text-align: center;}.query span {font-size: 18px;}.input-wrap {position: relative;}.input-wrap span {position: absolute;right: 15px;bottom: 15px;font-size: 12px;}.input-wrap i {font-size: 20px;font-style: normal;}</style></head><body><div id="app"><!-- 条件选择框 --><div class="query"><span>翻译成的语言:</span><select><option value="italy">意大利</option><option value="english">英语</option><option value="german">德语</option></select></div><!-- 翻译框 --><div class="box"><div class="input-wrap"><textarea v-model="obj.words"></textarea><span><i>⌨️</i>文档翻译</span></div><div class="output-wrap"><div class="transbox">{{ result }}</div></div></div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>// 接口地址:https://applet-base-api-t.itheima.net/api/translate// 请求方式:get// 请求参数:// (1)words:需要被翻译的文本(必传)// (2)lang: 需要被翻译成的语言(可选)默认值-意大利// -----------------------------------------------const app = new Vue({el: '#app',data: {// words: ''obj: {words: ''},result: '', // 翻译结果// timer: null // 延时器id},// 具体讲解:(1) watch语法 (2) 具体业务实现watch: {// 该方法会在数据变化时调用执行// newValue新值, oldValue老值(一般不用)// words (newValue) {//   console.log('变化了', newValue)// }'obj.words' (newValue) {// console.log('变化了', newValue)// 防抖: 延迟执行 → 干啥事先等一等,延迟一会,一段时间内没有再次触发,才执行clearTimeout(this.timer)this.timer = setTimeout(async () => {const res = await axios({url: 'https://applet-base-api-t.itheima.net/api/translate',params: {words: newValue}})this.result = res.data.dataconsole.log(res.data.data)}, 300)}}})</script></body>
</html>

完整写法

添加额外配置项

deep:true 对复杂类型深度监视

immediate:true  初始化立刻执行一次handler方法

<!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>027watch侦听器完整写法</title><style>* {margin: 0;padding: 0;box-sizing: border-box;font-size: 18px;}#app {padding: 10px 20px;}.query {margin: 10px 0;}.box {display: flex;}textarea {width: 300px;height: 160px;font-size: 18px;border: 1px solid #dedede;outline: none;resize: none;padding: 10px;}textarea:hover {border: 1px solid #1589f5;}.transbox {width: 300px;height: 160px;background-color: #f0f0f0;padding: 10px;border: none;}.tip-box {width: 300px;height: 25px;line-height: 25px;display: flex;}.tip-box span {flex: 1;text-align: center;}.query span {font-size: 18px;}.input-wrap {position: relative;}.input-wrap span {position: absolute;right: 15px;bottom: 15px;font-size: 12px;}.input-wrap i {font-size: 20px;font-style: normal;}</style></head><body><div id="app"><!-- 条件选择框 --><div class="query"><span>翻译成的语言:</span><select v-model="obj.lang"><option value="italy">意大利</option><option value="english">英语</option><option value="german">德语</option></select></div><!-- 翻译框 --><div class="box"><div class="input-wrap"><textarea v-model="obj.words"></textarea><span><i>⌨️</i>文档翻译</span></div><div class="output-wrap"><div class="transbox">{{ result }}</div></div></div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>// 需求:输入内容,修改语言,都实时翻译// 接口地址:https://applet-base-api-t.itheima.net/api/translate// 请求方式:get// 请求参数:// (1)words:需要被翻译的文本(必传)// (2)lang: 需要被翻译成的语言(可选)默认值-意大利// -----------------------------------------------const app = new Vue({el: '#app',data: {obj: {words: '你好',lang: 'italy'},result: '', // 翻译结果},watch: {obj: {deep: true, // 深度监视immediate: true, // 立刻执行,一进入页面handler就立刻执行一次handler (newValue) {clearTimeout(this.timer)this.timer = setTimeout(async () => {const res = await axios({url: 'https://applet-base-api-t.itheima.net/api/translate',params: newValue})this.result = res.data.dataconsole.log(res.data.data)}, 300)}}// 'obj.words' (newValue) {//   clearTimeout(this.timer)//   this.timer = setTimeout(async () => {//     const res = await axios({//       url: 'https://applet-base-api-t.itheima.net/api/translate',//       params: {//         words: newValue//       }//     })//     this.result = res.data.data//     console.log(res.data.data)//   }, 300)// }}})</script></body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/636309.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java Web 网页设计

不要让追求之舟停泊在幻想的港湾 而应扬起奋斗的风帆 驶向现实生活的大海 网页设计 1.首先 添加框架支持 找到目录右键添加 找到Web Application选中 点击OK 然后 编辑设置 找到Tomcat--local 选中 点击OK 名称可以自己设置 找到对应文件夹路径 把Tomcat添加到项目里面 因为…

一次Redis访问超时的“捉虫”之旅

01 引言 作为后端开发人员&#xff0c;对Redis肯定不陌生&#xff0c;它是一款基于内存的数据库&#xff0c;读写速度非常快。在爱奇艺海外后端的项目中&#xff0c;我们也广泛使用Redis&#xff0c;主要用于缓存、消息队列和分布式锁等场景。最近在对一个老项目使用的docker镜…

Java——数组

数组是一块连续的内存&#xff0c;用来存储相同类型的数据 一、数组的定义 数组的创建 T[] 数组名 new T[N]; T&#xff1a;表示数组中存放元素的类型 T[]&#xff1a;表示数组的类型 N&#xff1a;表示数组的长度 数组的初始化 数组的初始化主要分为动态初始化和静态初始…

链表基础4——带头双向循环链表

什么是带头双向循环链表 我们直接看图片 定义结点类型 typedef int LTDataType;//存储的数据类型typedef struct ListNode {LTDataType data;//数据域struct ListNode* prev;//前驱指针struct ListNode* next;//后继指针 }ListNode;链表的初始化 //创建一个新结点 ListNod…

社交媒体数据恢复:Dust

社交媒体数据恢复&#xff1a;Dust/CYBER DUST 网络灰尘&#xff1a;更安全的发短信场所 概述 CYBER DUST 让您掌控自己的数字生活。我们相信网络生活就是现实生活&#xff0c;因此只有您应该控制有关您的信息。我们的用户受到保护——不用担心被窥探、数据挖掘、粗略的黑客&…

Golang | Leetcode Golang题解之第42题接雨水

题目&#xff1a; 题解: func trap(height []int) (ans int) {n : len(height)if n 0 {return}leftMax : make([]int, n)leftMax[0] height[0]for i : 1; i < n; i {leftMax[i] max(leftMax[i-1], height[i])}rightMax : make([]int, n)rightMax[n-1] height[n-1]for i…

06 MapStream递归

Collections(集合工具类) 可变参数 就是一种特殊形参&#xff0c;定义在方法、构造器的形参列表里&#xff0c;定义格式是&#xff1a;方法名(数据类型… 形参名称){ } 可变参数的特点和好处 **特点&#xff1a;**可以不传数据给它&#xff1b;可以传一个或者同时传多个数据给…

Edge 浏览器使用方法和经验技巧

目前我已经将主力浏览器从火狐更换到Edge&#xff0c;本文将会根据我自己的使用经验来不断更新完善&#xff0c;内容包括下载、常用插件、使用技巧和常见问题等 下载安装 Edge是win10内置的浏览器&#xff0c;因此多数人不需要下载&#xff0c;如果你的电脑并没有安装&#x…

LearnOpenGL(二)之三角形

一、重要概念 顶点数组对象&#xff1a;Vertex Array Object&#xff0c;VAO顶点缓冲对象&#xff1a;Vertex Buffer Object&#xff0c;VBO元素缓冲对象&#xff1a;Element Buffer Object&#xff0c;EBO 或 索引缓冲对象 Index Buffer Object&#xff0c;IBO 以数组的形式…

《2024最新Java面试题及答案(带完整目录)》

2024最新Java面试题及答案有史以来见过的最全面试题 获取链接&#xff1a;《2024最新Java面试题及答案&#xff08;带完整目录&#xff09;》 更多技术书籍&#xff1a;技术书籍分享&#xff0c;前端、后端、大数据、AI、人工智能... ​ ​ ​ 4.1.9.8. 可重入锁&#xff…

【KMP】优质模板推荐+解读

KMP – y神模板 引言&#xff1a;由于本人与4月20日前周五的一节数据结构课中偶然听到了老师讲kmp这个算法的概念并且发现老师讲的听不懂一点儿导致异常难受&#xff0c;于是花了两天左右自行弄懂了kmp算法的逻辑&#xff0c;并写下本文以便以后复习&#xff0c;并作留念。 声明…

数据结构10:堆和堆排序

文章目录 树的概念及结构树的概念树的相关概念树的表示树在实际中的应用表示文件系统的目录树结构 二叉树概念及结构概念特殊的二叉树二叉树的性质二叉树的存储结构顺序存储链式存储 二叉树的顺序结构及实现二叉树的顺序结构堆的概念及结构 堆的实现堆的插入堆的删除堆的创建向…