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

embedded/2024/10/11 11:21:01/

目录

指令

指令修饰符

按键修饰符

​编辑

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/embedded/5509.html

相关文章

精通MongoDB聚合操作API:深入探索高级技巧与实践

MongoDB 聚合操作API提供了强大的数据处理能力&#xff0c;能够对数据进行筛选、变换、分组、统计等复杂操作。本文介绍了MongoDB的基本用法和高级用法&#xff0c;高级用法涵盖了setWindowFields、merge、facet、expr、accumulator窗口函数、结果合并、多面聚合、查询表达式在…

Python 操作 json 数据

在Python中&#xff0c;操作JSON数据主要包括序列化&#xff08;将Python对象转换为JSON格式&#xff09;和反序列化&#xff08;将JSON字符串转换回Python对象&#xff09;。 以下是使用Python内置的json模块进行这些操作的基本示例&#xff1a; JSON 序列化 (Serialization…

从入门到精通C++之类和对象(续)

目录 初始化列表构造函数&#xff1f;拷贝构造&#xff1f;浅谈explicit关键字友元 内部类static成员总结 初始化列表 引入初始化列表&#xff1a;简化代码&#xff0c;提高效率 在编程中&#xff0c;初始化列表是一种用于在创建对象时初始化成员变量的快捷方式。通过初始化列…

智能生活新体验:小米香薰加湿器技术解码

在现代家居生活中&#xff0c;科技与舒适性日益交织&#xff0c;智能家居产品成为提升生活品质的重要工具。小米香薰加湿器作为一款集科技与生活美学于一体的产品&#xff0c;其独特的设计和多功能性受到了广泛欢迎。今天&#xff0c;我们就来详细拆解这款融合了科技与香薰元素…

C语言第六章之内存分布,内存管理

内存分布 C代码编译过程 预处理 宏定义展开、头文件展开、条件编译&#xff0c;这里并不会检查语法 编译 检查语法&#xff0c;将预处理后文件编译生成汇编文件 汇编 将汇编文件生成目标文件(二进制文件) 链接 将目标文件链接为可执行程序 进程的内存分布 程序运行起来(…

NotePad++联动ABAQUS

Abaqus 中脚本运行 1. 命令区kernel Command Line Interface &#xff08;KCLI&#xff09; execfile(C:\\temp\second develop\chapter2\pyTest1.py)2. CAE-Run Script File->Run Script 3. Abaqus command Abaqus cae noGUIscript.py(前后处理都可)Abaqus Python scr…

STM32G431RBT6之时钟树配置与生成工程

默认大家都下载了蓝桥杯嵌入式资源包了哈. 首先,打开cubumx,修改RCC与SYS. 打开并观察原理图,发现晶振是24Mhz. 第一步,打开Clock Configuration. 第二步,修改晶振为原理图相对应的24Mhz. 第三步,切换到HSE. 第四步,切换到PLLCLK. 第五步,设置HCLK为80Mhz(15届真题要求为8…

C语言优先级表格(速查)

优先级表格 优先级 运算符 描述综合性&#xff11;&#xff0b;&#xff0b; &#xff0d;&#xff0d;后缀自增与自减从左向右( )函数调用[ ]数组下标&#xff0e;结构体与联合体成员访问&#xff0d;&#xff1e;结构体与联合体成员通过指针访问( type ) { list }复合字面…