12 Vue3中的监听器

概述

Vue watchers programmatically observe component data and run whenever a particular property changes. Watched data can contain two arguments: oldVal and newVal. This can help you when writing expressions to compare data before writing or binding new values. Watchers can observe objects as well as other types, such as string, number, and array types.

Vue 观察器以编程方式观察组件数据,并在特定属性发生变化时运行。观察数据可包含两个参数:oldVal 和 newVal。这有助于您在编写表达式时,在写入或绑定新值之前比较数据。观察者可以观察对象以及其他类型,如字符串、数字和数组类型。

To clean up your watcher code, you can assign a handler argument to a defined component’s method, which is considered best practice for large projects.

要清理观察者代码,可以为已定义组件的方法指定一个处理程序参数,这被认为是大型项目的最佳做法。

Watchers complement the usage of computed data since they passively observe values and cannot be used as normal Vue data variables, while computed data must always return a value and can be looked up. Remember not to use arrow functions if you need the Vue context of this.

观察者是对计算数据使用的补充,因为它们被动地观察值,不能作为普通的 Vue 数据变量使用,而计算数据必须始终返回值,并且可以查询。如果需要 Vue 上下文,切记不要使用箭头函数。

The following example demonstrates the immediate and deep optional keys; if any key inside the myDataProperty object were to change, it would trigger a console log:

下面的示例演示了即时和深度可选键;如果 myDataProperty 对象中的任何键发生变化,都会触发控制台日志:

<script>
export default {data() {return {}},watch: {myDataProperty: {handler: function(newVal, oldVal) {console.log('myDataProperty changed:', newVal, oldVal)},immediate: true,deep: true},}
}
</script>

练习:监听器的基本使用

In this exercise, you will use watcher arguments to watch data properties for changes, then use this watcher to set variables via a method.

在本练习中,您将使用观察者参数来监视数据属性的变化,然后使用该观察者通过方法设置变量。

Let’s create a new Vue component called Exercise2-03 by adding the Exercise2-03.vue file to the ./src/components/ folder.

让我们在 ./src/components/ 文件夹中添加 Exercise2-03.vue 文件,创建一个名为 Exercise2-03 的新 Vue 组件。

修改App.vue,引入该组件并进行渲染:

<script setup>
import Exercise from "./components/Exercise2-03.vue";
</script>
<template><Exercise/>
</template>

Open Exercise2-03.vue and let’s create the code block structure for the Vue component, as follows:

打开 Exercise2-03.vue,创建 Vue 组件的代码块结构如下:

<template>
</template>
<script>
export default {
}
</script>

Set up the document by adding a discount and an oldDiscount data:

通过添加折扣和旧折扣数据来设置文档:

<template><div class="container"><h1>Shop Watcher</h1><div>Black Friday sale<strike>Was {{ oldDiscount }}%</strike><strong> Now {{ discount }}% OFF</strong></div></div>
</template>
<script>
export default {data() {return {oldDiscount: 0,discount: 5,}},
}
</script>

We want to listen to the changes in the discount property. This can be achieved by adding it to the watch object and manually updating the oldDiscount value to oldValue received as follows:

我们希望监听折扣属性的变化。为此,我们可以将其添加到观察对象中,并将收到的 oldDiscount 值手动更新为 oldValue,如下所示:

<script>
export default {data() {return {oldDiscount: 0,discount: 5,}},watch: {discount(newValue, oldValue) {this.oldDiscount = oldValue},},
}
</script>

Now let’s add a component method called updateDiscount. Inside the method, set the oldDiscount data prop to this.discount + 5:

现在,让我们添加一个名为 updateDiscount 的组件方法。在该方法中,将 oldDiscount 数据道具设置为 this.discount + 5:

<script>
export default {data() {return {oldDiscount: 0,discount: 5,}},methods: {updateDiscount() {this.discount = this.discount + 5},},watch: {discount(newValue, oldValue) {this.oldDiscount = oldValue},},
}
</script>

Then bind this method to button using the @click directive to trigger this method whenever the user clicks on the button and respectively trigger the watcher:

然后使用 @click 指令将此方法绑定到按钮上,以便在用户点击按钮时触发此方法,并分别触发观察者:

<template><div class="container"><h1>Shop Watcher</h1><div>Black Friday sale<strike>Was {{ oldDiscount }}%</strike><strong> Now {{ discount }}% OFF</strong></div><button @click="updateDiscount">Increase Discount!</button></div>
</template>

Add some CSS stylings to make our component look pretty:

添加一些 CSS 样式,让我们的组件看起来更漂亮:

<template><div class="container"><h1>Shop Watcher</h1><div>Black Friday sale<strike>Was {{ oldDiscount }}%</strike><strong> Now {{ discount }}% OFF</strong></div><button @click="updateDiscount">Increase Discount!</button></div>
</template>
<script>
export default {data() {return {oldDiscount: 0,discount: 5,}},methods: {updateDiscount() {this.discount = this.discount + 5},},watch: {discount(newValue, oldValue) {this.oldDiscount = oldValue},},
}
</script><style scoped>
.container {margin: 0 auto;padding: 30px;max-width: 600px;font-family: 'Avenir', Helvetica, Arial, sans-serif;
}button {display: inline-block;background: rgb(235, 50, 50);border-radius: 10px;font-size: 14px;color: white;padding: 10px 20px;text-decoration: none;
}
</style>

In this exercise, we explored how we can use watchers to observe and dynamically manipulate data when it is changed by triggering other methods in the Vue component.

在本练习中,我们探索了如何使用观察者来观察数据,并在数据发生变化时通过触发 Vue 组件中的其他方法来动态处理数据。

Next, we will learn how to actively watch a specific nested property within a data object through deep watching.

接下来,我们将学习如何通过深度观察来主动观察数据对象中的特定嵌套属性。

监听嵌套的属性

When using Vue.js to watch a data property, you can observe changes belonging to nested keys of an object, rather than observing the changes to the object itself.

使用 Vue.js 观察数据属性时,你可以观察到属于对象嵌套键的变化,而不是观察对象本身的变化。

This is done by setting the optional deep property to true:

这可以通过将可选的 deep 属性设置为 true 来实现:

<script>
export default {data() {return {organization: {name: 'ABC',employees: ['Jack', 'Jill']}}},watch: {organization: {handler(v) {this.sendIntercomData()},deep: true,immediate: true,},},
}
</script>

This code example demonstrates how we watch all available keys inside the organization data object for changes. If the name property inside organization changes, the organization watcher will trigger.

本代码示例演示了如何观察组织数据对象中所有可用键的变化。如果组织内部的 name 属性发生变化,组织观察器就会触发。

If you do not need to observe every key inside an object, it is more performant to assign a watcher to a specific key by specifying it following the syntax <object>.<key> string. For example, you may allow a user to edit their company name and trigger an API call when that specific key’s value has been modified.

如果不需要观察对象中的每个键,那么按照 <object>.<key> 字符串的语法为特定键指定观察者会更有效。例如,您可以允许用户编辑自己的公司名称,并在特定键值被修改时触发 API 调用。

In the following example, the watcher is explicitly observing the name key of the organization object:

在下面的示例中,观察者明确观察组织对象的名称键:

<script>
export default {data() {return {organization: {name: 'ABC',employees: ['Jack', 'Jill']}}},watch: {'organization.name': {handler: function(v) {this.sendIntercomData()},immediate: true,},},
}
</script>

练习:监听对象的嵌套属性

In this exercise, you will use watchers to observe keys within an object, which will update when a user triggers a method within the UI.

在本练习中,您将使用观察者来观察对象中的键,当用户触发用户界面中的方法时,这些键就会更新。

Let’s create a new Vue component called Exercise2-04 by adding the Exercise2-04.vue file to the ./src/components/ folder:

让我们在 ./src/components/ 文件夹中添加 Exercise2-04.vue 文件,创建一个名为 Exercise2-04 的新 Vue 组件:

在App.vue中,引入该组件并渲染:

<script setup>
import Exercise from "./components/Exercise2-04.vue";
</script>
<template><Exercise/>
</template>

In Exercise2-04.vue, let’s start by defining a product object that contains price and label, and a discount key. Output these values into the template:

在 Exercise2-04.vue 中,我们先定义一个包含价格、标签和折扣键的产品对象。将这些值输出到模板中:

<template><div class="container"><h1>Deep Watcher</h1><div><h4>{{ product.label }}</h4><h5>${{ product.price }} (${{ discount }}Off)</h5></div></div>
</template>
<script>
export default {data() {return {discount: 0,product: {price: 25,label: 'Blue juice',},}},
}
</script>

Add CSS styling to our component:

为我们的组件添加 CSS 样式:

<style scoped>
.container {margin: 0 auto;padding: 30px;max-width: 600px;font-family: 'Avenir', Helvetica, sans-serif;
}button {display: inline-block;background: rgb(235, 50, 50);border-radius: 10px;font-size: 14px;color: white;padding: 10px 20px;text-decoration: none;
}
</style>

Now let’s set up a button that will modify the price of the product. We achieve this by adding a button element with a click event bound to an updatePrice method that decrements the value of the price:

现在,让我们设置一个按钮来修改产品的价格。为此,我们添加了一个按钮元素,其点击事件绑定到一个 updatePrice 方法上,该方法会递减价格值:

<template><div class="container"><h1>Deep Watcher</h1><div><h4>{{ product.label }}</h4><h5>${{ product.price }} (${{ discount }} Off)</h5></div><button @click="updatePrice">Reduce Price!</button></div>
</template>
<script>
export default {data() {return {discount: 0,product: {price: 25,label: 'Blue juice',},}},methods: {updatePrice() {if (this.product.price < 1) returnthis.product.price--},},
}
</script>

Time for the nested watcher. We will watch the product object’s price, and increment the discount data prop:

是时候使用嵌套监视器了。我们将观察产品对象的价格,并递增折扣数据道具:

<script>
export default {data() {return {discount: 0,product: {price: 25,label: 'Blue juice',},}},methods: {updatePrice() {if (this.product.price < 1) returnthis.product.price--},},// 新增的代码watch: {'product.price'() {this.discount++},},
}
</script>

In this exercise, we used watchers to observe a key inside an object and then set new data with or without using the optional arguments parsed by the watcher.

在本练习中,我们使用观察者观察对象内部的键,然后使用或不使用观察者解析的可选参数设置新数据。

In the next section, we will explore how to fetch and handle data using the Vue component’s async methods.

在下一节中,我们将探讨如何使用 Vue 组件的异步方法获取和处理数据。

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

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

相关文章

英文论文降重修改技巧 papergpt

大家好&#xff0c;今天来聊聊英文论文降重修改技巧&#xff0c;希望能给大家提供一点参考。 以下是针对论文重复率高的情况&#xff0c;提供一些修改建议和技巧&#xff0c;可以借助此类工具&#xff1a; 英文论文降重修改技巧 作为网站编辑&#xff0c;我们经常需要处理大量…

冒泡排序法

1.数组排序 题目描述 对数组的元素按从小到大进行排序。输入有两行 第一行有一个整数n( 5 < n < 10 ) 第二行有n个整数输出输出更新后的数组 样例 输入复制 8 1 2 3 6 8 7 4 5 输出复制 1 2 3 4 5 6 7 8 #include<iostream> using namespace std; int main(…

遥感图像之多模态检索AMFMN(支持关键词、句子对图像的检索)论文阅读、环境搭建、模型测试、模型训练

一、论文阅读 1、摘要背景 遥感跨模态文本图像检索以其灵活的输入和高效的查询等优点受到了广泛的关注。然而&#xff0c;传统的方法忽略了遥感图像多尺度和目标冗余的特点&#xff0c;导致检索精度下降。为了解决遥感多模态检索任务中的多尺度稀缺性和目标冗余问题&#xff…

linux 阻塞io

睡眠的介绍 对于一个进程"睡眠"意味着什么? 当一个进程被置为睡眠, 它被标识为处于一个特殊的状 态并且从调度器的运行队列中去除. 直到发生某些事情改变了那个状态, 这个进程将不被 在任何 CPU 上调度, 并且, 因此, 将不会运行. 一个睡着的进程已被搁置到系统的一…

Python中的并发编程是什么,如何使用Python进行并发编程?

并发编程是指在一个程序中同时运行多个任务的能力。在Python中&#xff0c;可以使用threading模块进行并发编程。以下是一个简单的例子&#xff1a; import threadingdef print_numbers():for i in range(10):print(i)def print_letters():for letter in abcdefghij:print(let…

CSS3 2D变形 过渡 动画

​​​​​ transform(2D变形)概述translate()平移scale()缩放skew()倾斜rotate()旋转transform-origin中心原点 CSS3 2D变形 3D变形 过渡 动画 在CSS3中&#xff0c;动画效果包括4个部分&#xff1a;变形&#xff08;transform&#xff09;、3D变形、过渡&#xff08;transit…

NX二次开发(NXOpenC++) - 切换制图模块方法

一、概述 在NX二次开发过程中&#xff0c;在某些应用场景中,经常要在建模环境和制图环境间的相互切换&#xff0c;NX切换至制图模块的方法有多种&#xff0c;不同的NX版本有所不同&#xff0c;有的是同一种方法支持多个版本&#xff0c;本技巧将列举切换至制图模块的各种方法。…

PMP项目管理 - 采购管理

系列文章目录 PMP项目管理 - 质量管理 PMP项目管理 - 采购管理 PMP项目管理 - 资源管理 PMP项目管理 - 风险管理 现在的一切都是为将来的梦想编织翅膀&#xff0c;让梦想在现实中展翅高飞。 Now everything is for the future of dream weaving wings, let the dream fly in…

专业面试刷题网站程序源码

介绍&#xff1a; 一个干净的面试刷题网站&#xff01;专业面试刷题网站&#xff0c;助你成为面试达人&#xff01;支持自由组卷、在线刷题、校招社招斩获大厂offer&#xff0c;求职必备! 用这个刷题代码&#xff0c;助你早日打进狼厂、鹅厂等各大厂&#xff0c;薪水直接等级…

【剪映】点滴剪时光

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

敏捷开发-任务拆解、工作量评估和任务指派

在之前的文章我首先讲了1)敏捷的第一步-每日站立会&#xff0c;然后讲了如何2)用看板管理项目或者管理自己的工作待办&#xff0c;今天是第三个主题&#xff0c;讲如何3)在实际项目中做任务拆解、估时和工作指派。 任务拆解和评估 任务拆解和评估是一项需要非常细致、需要经验…

bin后缀的固件怎么解包和封包

bin后缀的固件解包和封包可以通过以下步骤进行&#xff1a; 解包&#xff1a; 使用解包工具&#xff1a;有许多解包工具可用于处理bin文件&#xff0c;例如UltralISO等。这些工具可以将bin文件解包为单个文件。选择目标文件夹&#xff1a;在解包之前&#xff0c;选择一个目标…

C# 如何控制多线程同步执行

写在前面 使用Task类来控制多线程的同步执行&#xff0c;可应用于多任务分发执行后&#xff0c;再做归并处理。Tas既拥有线程池的优点&#xff0c;同时也解决了使用ThreadPool不易控制的弊端&#xff1b;可以非常简便并可靠地实现多线程的顺序执行。 代码实现 public class …

王道考研--》单链表课后习题C语言代码实现(冲刺)

考研是许多计算机科学专业学生追求高学历、寻求更好就业前景的途径。在考研过程中&#xff0c;数据结构是一个非常重要的科目&#xff0c;而代码实现题更是其中的难点之一。在这篇文章中&#xff0c;我们将探讨如何通过实现数据结构代码问题来提升考研成绩。无论您是否有编程经…

设计模式模板方法模式讲解和代码示例

引言 模版方法是一种行为设计模式, 它在基类中定义了一个算法的框架, 允许子类在不修改结构的情况下重写算法的特定步骤。 Java语言 使用示例: 模版方法模式在 Java 框架中很常见。 开发者通常使用它来向框架用户提供通过继承实现的、 对标准功能进行扩展的简单方式。 这…

K8S(十)—容器探针

这里写目录标题 容器探针&#xff08;probe&#xff09;检查机制探测结果探测类型何时该使用存活态探针?何时该使用就绪态探针?何时该使用启动探针&#xff1f; 使用exechttptcpgrpc使用命名端口 使用启动探针保护慢启动容器定义就绪探针配置探针HTTP 探测TCP 探测探针层面的…

JavaScript中的变量提升:解析、应用及示例

JavaScript中的变量提升是一个常见但容易令人困惑的概念。在本文中&#xff0c;我们将深入探讨JavaScript中的变量提升&#xff0c;包括其含义、用途以及通过代码示例进行解释。 什么是变量提升&#xff1f; 在JavaScript中&#xff0c;变量提升是指在代码执行前将变量声明提…

硬件基础:光耦、可控硅、继电器、达林顿管、干簧管

光耦 光电耦合器&#xff08;optical coupler&#xff0c;英文缩写为OC&#xff09;亦称光电隔离器&#xff0c;简称光耦。 光电耦合器是一种把发光器件和光敏器件封装在同一壳体内&#xff0c; 中间通过电→光→电的转换来传输电信号的半导体光电子器件。其中&#xff0c;发光…

re:Invent2023大会隆重推出自研芯片Graviton4和Trainium2

目录 一、前言 二、体验Graviton系列产品 &#xff08;一&#xff09;创建普通的EC2实例 &#xff08;二&#xff09;创建Graviton处理器的EC2实例 &#xff08;三&#xff09;远程到服务器 方式1&#xff1a;创建成功时连接 方式2&#xff1a;SSH客户端 方式3&#xff1a;正确…

基于FPGA的视频接口之高速IO(SATA)

简介 本章节是对于高速IO接口应用的一个扩展,目前扩展为SATA(SSD硬盘,机械硬盘不能使用)。通俗易懂的讲,即把SSD硬盘当做大型的Nand Flash来处理,不格式化硬盘,直接以地址和数据的格式,在SATA盘中写入数据,该数据不能被Window和linux直接识别,需单独编写App来查看SSD…