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

news/2024/9/23 14:31:38/

目录

指令

指令修饰符

按键修饰符

​编辑

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.ppmy.cn/news/1427448.html

相关文章

内网云盘如何内网穿透实现公网访问

云盘是一种专业的互联网存储工具&#xff0c;是互联网云技术的产物&#xff0c;它通过互联网为企业和个人提供信息的存储、读取、下载等服务&#xff0c;具有安全稳定、海量存储的特点。随着企业信息化发展&#xff0c;云盘系统需求不断扩大&#xff0c;相关系统软件被广泛应用…

FPGA - ZYNQ 基于EMIO的PS和PL交互

前言&#xff1a; Xilinx ZYNQ系列的芯片&#xff0c;GPIO分为 MIO 、EMIO、AXI_GPIO三种方式。 MIO &#xff1a;固定管脚&#xff0c;属于PS端&#xff0c;也就是ARM端。 EMIO &#xff1a;通过PL扩展&#xff0c;使用时需要分配PL(FPGA)管脚&#xff0c;消耗PL端资源。…

怎么使用JMeter进行性能测试?

一、简介 JMeter是Apache软件基金会下的一款开源的性能测试工具&#xff0c;完全由Java开发。它专注于对我们应用程序进行负载测试和性能测量&#xff0c;最初设计用于web应用程序&#xff0c;现在已经扩展到其他测试功能&#xff0c;比如&#xff1a;FTP、Database和LDAP等。…

[网络安全]-059-安全大模型以及训练数据集

Contents Tools IntegratedAuditReconnaissanceOffensiveDetectingPreventingSocial EngineeringReverse EngineeringInvestigationFixAssessmentCases ExperimentalAcademicB

R语言中的execl数据转plink

文章目录 带出外部连接的方式添加列的方式从列表中选出对应的数据信息查看变量信息没有成功 带出外部连接的方式 点击这个黄色的按钮就可以弹出外部链接的方式 添加列的方式 创建一个数据框的方式 我们创建一个三行三列的数据方式 df <- data.frame(name c("Alice&…

iOS 知识点---闭包

Swift 中的闭包原理&#xff1a; 闭包是一种自包含的代码块&#xff0c;它可以捕获其所在上下文中的常量和变量&#xff0c;并且可以在代码中作为参数传递&#xff0c;也可以作为函数的返回值。闭包在 Swift 中与 C 和 Objective-C 中的代码块&#xff08;blocks&#xff09;、…

论文笔记:Large Language Model for Participatory Urban Planning

202402 arxiv 大模型城市规划 引入了一个基于LLM的多代理协作框架&#xff0c;模拟规划师和数千名具有不同特征和背景的居民&#xff0c;用于参与式城市规划——>生成考虑居民多样化需求的城市区域土地利用规划为了提高讨论的效率&#xff0c;论文采用了鱼缸讨论机制&#…

C++笔记打卡第14天(文件管理、职工操作系统)

1.文本文件(写文件) 文件类型分为两种&#xff1a; 文本文件&#xff1a;文件以文本的ASCII码形式存储在计算机中二进制文件&#xff1a;文件以文本的二进制形式存储在计算机中&#xff0c;用户一般不能直接读懂它 操作文件的三大类 ofstream&#xff1a;写操作ifstream&am…