03 Vue3中的生命周期函数

概述

The Vue component lifecycle events happen during a component’s lifecycle, from creation to deletion. They allow us to add callbacks and side effects at each stage of the component’s life when necessary.

Vue 组件生命周期事件发生在组件从创建到删除的生命周期中。必要时,我们可以在组件生命周期的每个阶段添加回调和副作用。

组件事件触发顺序

setup

This event runs before all other hooks, including beforeCreate. It doesn’t have access to this instance since the instance has not yet been created at this point. It is mainly for using Composition API and is treated in the same way Vue treats script setup.

该事件在所有其他钩子(包括 beforeCreate)之前运行。它无法访问此实例,因为此时实例尚未创建。它主要用于使用 Composition API,处理方式与 Vue 处理脚本设置的方式相同。

beforeCreate

This runs when your component has been initialized. data has not been made reactive and events are not set up in your DOM.

该功能在组件初始化时运行,此时数据尚未被反应,DOM 中也未设置事件。

created

You will be able to access reactive data and events, but the templates and DOM are not mounted or rendered. This hook is generally good to use when requesting asynchronous data from a server since you will more than likely want this information as early as possible before the virtual DOM is mounted.

您可以访问反应式数据和事件,但模板和 DOM 不会加载或渲染。一般来说,从服务器请求异步数据时适合使用此钩子,因为您很可能会在虚拟 DOM 挂载之前尽早获得这些信息。

beforeMount

A very uncommon hook, as it runs directly before the first render of your component and is not called Server-Side Rendering.

这是一个非常不常见的钩子,因为它直接运行在组件的第一次渲染之前,而且不称为服务器端渲染。

mounted

Mounting hooks are among the most common hooks you will use since they allow you to access your DOM elements so that non-Vue libraries can be integrated.

安装钩子是您最常用的钩子之一,因为它们允许您访问 DOM 元素,以便集成非 Vue 库。

beforeUpdate

This runs immediately after a change to your component occurs and before it has been re-rendered. It’s useful for acquiring the state of reactive data before it has been rendered.

在组件发生变化后、重新渲染前,它会立即运行。这对于在渲染之前获取反应数据的状态非常有用。

updated

It runs immediately after the beforeUpdate hook and re-renders your component with new data changes.

它在 beforeUpdate 钩子之后立即运行,并根据新的数据变化重新渲染组件。

beforeUnMount

This is fired directly before unmounting your component instance. The component will still be functional until the unmounted hook is called, allowing you to stop event listeners and subscriptions to data to avoid memory leaks. Note this event is called beforeDestroy in Vue 2.x.

该钩子会在卸载组件实例前直接触发。在卸载钩子被调用之前,组件仍将正常运行,从而允许您停止事件侦听器和数据订阅,以避免内存泄漏。请注意,在 Vue 2.x 中,该事件被称为 beforeDestroy。

unmounted

All the virtual DOM elements and event listeners have been cleaned up from your Vue instance. This hook allows you to communicate that to anyone or any element that needs to know this has been done. This event in Vue 2.x is called destroyed.

Vue 实例中的所有虚拟 DOM 元素和事件侦听器都已清理完毕。通过此钩子,您可以将此信息传达给需要知道此操作已完成的任何人或任何元素。在 Vue 2.x 中,该事件被称为 destroyed。

练习:使用Vue生命周期函数控制数据

In this exercise, we will be learning how and when to use Vue’s lifecycle hooks, and when they are triggered by using JavaScript alerts. By the end of the exercise, we will be able to understand and use multiple Vue lifecycle hooks.

在本练习中,我们将学习如何以及何时使用 Vue 的生命周期钩子,以及何时通过使用 JavaScript 警报来触发这些钩子。练习结束时,我们将能够理解并使用多个 Vue 生命周期钩子。

Create a new Vue component file named Exercise1-10.vue in the src/components directory.

在 src/components 目录中新建一个名为 Exercise1-10.vue 的 Vue 组件文件。

修改App.vue,引入该组件并使用:

<script setup>
import Exercise from "./components/Exercise1-10.vue";
</script>
<template><Exercise/>
</template>

Inside Exercise1-10.vue, we start by creating an array of data to iterate through in a list element, set the key to n, and output the {{item}} value inside of the <li> element using curly braces:

在 Exercise1-10.vue 中,我们首先创建一个数据数组,在列表元素中进行遍历,将键设置为 n,然后使用大括号在 <li> 元素中输出 {{item}} 值:

<template><div><h1>Vue Lifecycle hooks</h1><ul><li v-for="(item, n) in list" :key="n">{{ item }}</li></ul></div>
</template>
<script>
export default {data() {return {list: ['Apex Legends','A Plague Tale: Innocence','ART SQOOL','Baba Is You','Devil May Cry 5','The Division 2','Hypnospace Outlaw','Katana ZERO',],}}
}
</script>

Add beforeCreated() and created() as properties below the data() function. Set an alert or console log inside these hooks so that you can see when they are being triggered:

在 data() 函数下方添加 beforeCreated() 和 created() 作为属性。在这些钩子中设置警报或控制台日志,以便查看它们何时被触发:

<script>
export default {data() {return {list: ['Apex Legends','A Plague Tale: Innocence','ART SQOOL','Baba Is You','Devil May Cry 5','The Division 2','Hypnospace Outlaw','Katana ZERO',],}},beforeCreate() {alert('beforeCreate: data is static, thats it')},created() {alert('created: data and events ready, but no DOM')},
}
</script>

Define beforeMount() and mounted() in the same way as in step 6. Set an alert or console log inside of these hooks so that you can see when they are being triggered:

以与步骤 6 相同的方式定义 beforeMount() 和 mounted()。在这些钩子中设置警报或控制台日志,以便查看它们何时被触发:

<script>
export default {data() {return {list: ['Apex Legends','A Plague Tale: Innocence','ART SQOOL','Baba Is You','Devil May Cry 5','The Division 2','Hypnospace Outlaw','Katana ZERO',],}},beforeCreate() {alert('beforeCreate: data is static, thats it')},created() {alert('created: data and events ready, but no DOM')},beforeMount() {alert('beforeMount: $el not ready')},mounted() {alert('mounted: DOM ready to use')},
}
</script>

Add a new button element inside your <li> element that renders the item output. Use a @click directive to bind this button to a method called deleteItem and pass the item value as an argument:

<li> 元素中添加一个新的按钮元素,用于渲染项目输出。使用 @click 指令将此按钮绑定到名为 deleteItem 的方法,并将项目值作为参数传递:

<template><div><h1>Vue Lifecycle hooks</h1><ul><li v-for="(item, n) in list" :key="n">{{ item }}<button @click="deleteItem(item)">Delete</button></li></ul></div>
</template>

Add a method called deleteItem into a methods object above your hooks but below the data() function. Inside this function, pass value as an argument and filter out items from the list array based on this value. Then, replace the existing list with the new list:

在方法对象中添加名为 deleteItem 的方法,该方法位于钩子之上,但低于 data() 函数。在此函数中,将值作为参数传递,并根据此值从列表数组中筛选出项目。然后,用新列表替换现有列表:

<script>
export default {data() {return {list: ['Apex Legends','A Plague Tale: Innocence','ART SQOOL','Baba Is You','Devil May Cry 5','The Division 2','Hypnospace Outlaw','Katana ZERO',],}},beforeCreate() {alert('beforeCreate: data is static, thats it')},created() {alert('created: data and events ready, but no DOM')},beforeMount() {alert('beforeMount: $el not ready')},mounted() {alert('mounted: DOM ready to use')},methods: {deleteItem(value) {this.list = this.list.filter(item => item !==value)},},
}
</script>

Add beforeUpdate() and updated() as functions same as in step 9 and set an alert or console log inside them:

添加 beforeUpdate() 和 updated() 作为与步骤 9 相同的函数,并在其中设置警报或控制台日志:

<script>
export default {data() {return {list: ['Apex Legends','A Plague Tale: Innocence','ART SQOOL','Baba Is You','Devil May Cry 5','The Division 2','Hypnospace Outlaw','Katana ZERO',],}},beforeCreate() {alert('beforeCreate: data is static, thats it')},created() {alert('created: data and events ready, but no DOM')},beforeMount() {alert('beforeMount: $el not ready')},mounted() {alert('mounted: DOM ready to use')},beforeUpdate() {alert('beforeUpdate: we know an update is about to happen, and have the data')},updated() {alert('updated: virtual DOM will update after you click OK')},methods: {deleteItem(value) {this.list = this.list.filter(item => item !==value)},},
}
</script>

When you delete a list item by clicking on the Delete button in your browser, you should see these alerts. For example, when deleting the first item in the list, beforeUpdated will trigger.

点击浏览器中的删除按钮删除列表项时,应该会看到这些警报。例如,删除列表中的第一个项目时,beforeUpdated 将触发.

Continue adding beforeUnmount() and unmounted() to the component options as function properties. Set an alert or console log inside these hooks so that you can see when they are being triggered.

继续在组件选项中添加 beforeUnmount() 和 unmounted() 作为函数属性。在这些钩子中设置警报或控制台日志,以便查看它们何时被触发。

<script>
export default {data() {return {list: ['Apex Legends','A Plague Tale: Innocence','ART SQOOL','Baba Is You','Devil May Cry 5','The Division 2','Hypnospace Outlaw','Katana ZERO',],}},beforeCreate() {alert('beforeCreate: data is static, thats it')},created() {alert('created: data and events ready, but no DOM')},beforeMount() {alert('beforeMount: $el not ready')},mounted() {alert('mounted: DOM ready to use')},beforeUpdate() {alert('beforeUpdate: we know an update is about to happen, and have the data')},updated() {alert('updated: virtual DOM will update after you click OK')},beforeUnmount() {alert('beforeUnmount: about to blow up this component')},unmounted() {alert('unmounted: this component has been destroyed')},methods: {deleteItem(value) {this.list = this.list.filter(item => item !==value)},},
}
</script>

In this exercise, we learned what Vue lifecycle hooks are, when they trigger, and in what order they trigger. This will be useful in combination with triggering methods and controlling data within your Vue components.

在本练习中,我们了解了什么是 Vue 生命周期钩子、何时触发以及触发顺序。这将有助于在 Vue 组件中结合触发方法和控制数据。

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

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

相关文章

跟着官网学 Vue - 透传 Attributes

MyButton.vue 这是子组件&#xff0c;它是一个包含按钮的简单组件。它有一个按钮&#xff0c;当按钮被点击时&#xff0c;会触发 handleClick 方法。MyButton 组件中禁用了属性继承&#xff0c;以避免多次触发点击事件。 <!-- MyButton.vue --> <template><!-…

LeetCode day26

LeetCode day26 LCR 189. 设计机械累加器 请设计一个机械累加器&#xff0c;计算从 1、2… 一直累加到目标数值 target 的总和。注意这是一个只能进行加法操作的程序&#xff0c;不具备乘除、if-else、switch-case、for 循环、while 循环&#xff0c;及条件判断语句等高级功能…

Java并发(十九)----Monitor原理及Synchronized原理

1、Java 对象头 以 32 位虚拟机为例 普通对象 |--------------------------------------------------------------| | Object Header (64 bits) | |------------------------------------|-------------------------| | Mark W…

MySQL 报错 You can‘t specify target table for update in FROM clause解决办法

You can’t specify target table for update in FROM clause 其含义是&#xff1a;不能在同一表中查询的数据作为同一表的更新数 单独执行复合查询是正常的&#xff0c;如下&#xff1a; 但是当执行子查询删除命令时&#xff0c;报如下错误 DELETE FROM abpusers WHERE Id I…

简单介绍十款可以免费使用的API测试工具

API开发应该是后端开发最常见的工作&#xff0c;而调试和测试API是非常关键的&#xff0c;这篇文章简单介绍几款常用的工具以供大家参考。 SoapUI SoapUI是很老牌的工具的&#xff0c;在之前Webservice盛行的时候经常会用到。 现在官方推出了Pro版本的ReadyAPI&#xff0c;但要…

Python glob

参考文章&#xff1a; Python 中glob.glob()、glob.iglob&#xff08;&#xff09;的使用-CSDN博客 Python 中glob.glob()的使用 glob.glob(path)的功能&#xff1a; 返回符合path格式的所有文件的路径&#xff0c;以list存储返回。 path的表示方法&#xff1a; 利用匹配符…

数据科学知识库

​ 我的博客是一个技术分享平台&#xff0c;涵盖了机器学习、数据可视化、大数据分析、数学统计学、推荐算法、Linux命令及环境搭建&#xff0c;以及Kafka、Flask、FastAPI、Docker等组件的使用教程。 在这个信息时代&#xff0c;数据已经成为了一种新的资源&#xff0c;而机…

C#监听端口报错“以一种访问权限不允许的方式做了访问套接字的尝试”

C#编写的端口监听程序&#xff0c;平时都能正常运行&#xff0c;但最新操作系统更新补丁重启电脑后&#xff0c;运行程序报错“以一种访问权限不允许的方式做了访问套接字的尝试”&#xff0c;客户端程序也无法连接。   百度错误信息&#xff0c;给出的答案都是端口监听程序使…

ES分词查询

全文检索介绍 全文检索的发展过程&#xff1a; 数据库使用SQL语句&#xff1a;select * from table where data like “%检索内容%”出现lucene全文检索工具&#xff08;缺点&#xff1a;暴露的接口相对复杂&#xff0c;且没有效率&#xff09;出现分布式检索服务框架solr&am…

python读取excel数据 附实战代码

在Python中&#xff0c;可以使用pandas库来读取Excel文件中的数据。下面是一个简单的例子&#xff1a; import pandas as pd# 读取Excel文件 df pd.read_excel(example.xlsx)# 显示前5行数据 print(df.head())在上面的代码中&#xff0c;我们首先导入了pandas库&#xff0c;并…

ImageNet 数据集介绍

首先介绍ImageNet 1K数据集&#xff1a; This dataset provides access to ImageNet (ILSVRC) 2012 which is the most commonly used subset of ImageNet. This dataset spans 1000 object classes and contains 1,281,167 training images, 50,000 validation images and 10…

Java 第12章 异常 本章作业

1 编程 两数相除的异常处理 各自属于哪些异常&#xff1a; 数据格式不正确 NumberformatException 缺少命令行参数 ArrayIndexOutOfBoundsException 除0异常处理 ArithmeticException ArrayIndexOutOfBoundsException 为数组下标越界时会抛出的异常&#xff0c;可以在检测到命…

C语言学习day09:运算符优先级

运算符优先级&#xff1a; //& 假如设一个int a; 给a一个变量&#xff1b; &a取a对应的地址 优先级运算符名称或含义使用形式结合方向说明1[1,2,3,4]数组下标数组名[常量表达形式]左到右()圆括号(表达式)/函数名(形参).成员选择(对象)对象.成员名->成员选择(指…

C++继承中同名非静态成员与静态成员的处理(学习笔记)

非静态成员&#xff1a; 定义一个父类Base&#xff0c;子类Son class Base { public:int m_A 10;int m_B 200;void fun(){cout << "父类函数" << endl;}void fun(int a){cout << a << endl;} }; class Son : public Base { public:int m…

GO的sql注入盲注脚本

之间学习了go的语法 这里就开始go的爬虫 与其说是爬虫 其实就是网站的访问如何实现 因为之前想通过go写sql注入盲注脚本 发现不是那么简单 这里开始研究一下 首先是请求网站 这里貌似很简单 package mainimport ("fmt""net/http" )func main() {res, …

C语言数据结构-----二叉树(3)二叉树相关练习题

前言 前面详细讲述了二叉树的相关知识&#xff0c;为了巩固&#xff0c;做一些相关的练习题 文章目录 前言1.某二叉树共有 399 个结点&#xff0c;其中有 199 个度为 2 的结点&#xff0c;则该二叉树中的叶子结点数为&#xff1f;2.下列数据结构中&#xff0c;不适合采用顺序存…

文章解读与仿真程序复现思路——电力系统自动化EI\CSCD\北大核心《市场环境下考虑全周期经济效益的工业园区共享储能优化配置》

这个标题涉及到工业园区中共享储能系统的优化配置&#xff0c;考虑了市场环境和全周期经济效益。以下是对标题中各个要素的解读&#xff1a; 市场环境下&#xff1a; 指的是工业园区所处的商业和经济背景。这可能包括市场竞争状况、电力市场价格波动、政策法规等因素。在这一环…

WordCloud—— 词云

【说明】文章内容来自《机器学习入门——基于sklearn》&#xff0c;用于学习记录。若有争议联系删除。 wordcloud 是python的第三方库&#xff0c;称为词云&#xff0c;也成文字云&#xff0c;可以根据文本中的词频以直观和艺术化的形式展示文本中词语的重要性。 依赖于pillow …

kotlin 基础概览

继承类/实现接口 继承类和实现接口都是用的 : &#xff0c;如果类中没有构造器 ( constructor )&#xff0c;需要在父类类名后面加上 () &#xff1a; class MainActivity : BaseActivity(), View.OnClickListener 空安全设计 Kotlin 中的类型分为「可空类型」和「不可空类型」…

浏览器js中添加日志断点

一、需求 本地调试时&#xff0c;可以直接代码里使用console.log直接调试&#xff1b; 代码已更新到服务器&#xff0c;不想要提交代码&#xff0c;如何通过添加console.log调试呢 二、实现 使用浏览器添加日志断点的方式&#xff0c;当然vue这种打包的不可行哦 设置完成后…