当前位置: 首页 > backend >正文

前端基础之《Vue(7)—生命周期》

一、什么是生命周期

1、生命周期
组件从“生”到“死”的全过程。
每一个组件都有生命周期。

2、生命周期四大阶段
创建阶段:beforeCreate、created
挂载阶段:beforeMount、mounted
更新阶段:beforeUpdate、updated
销毁阶段:beforeDestroy、destroyed

3、生命周期图示

用人的一生来看生命周期:
beforeCreate:出生之前
created:出生了
beforeMount:到派出所办户口(生成虚拟DOM)
mounted:户口本上加了一页纸
......一岁一岁长大......
beforeDestroy:上帝召唤了
destroyed:G了,要重开了

(1)Init Events & Lifecycle
环境初始化,钩子函数、methods选项声明。
(2)Init injections & reactivity
组件上下文数据的注入,对data调用遍历,把data中所有的数据放在this中。
Vue的响应式劫持,就发生在这儿。加set、get钩子。
(3)Has "el" option?
组件有没有el选项。如果没有找mount()方法。
(4)Has "template" option?
找视图结构。视图模板。
(5)如果有template或者如果没有template
YES:Compile template into render function
编译这个模板,变成render方法。render方法用来生成虚拟DOM。
NO:Compile el's outerHTML as template
取当前el节点外部的HTML标签来做。
(6)Create vm.$el and replace "el" with it
调用render方法,创建虚拟DOM。并且对模板遍历指令收集,把指令中数据变成真实数据。
(7)when data changes
当data发生变化时。
(8)Virtual DOM re-render and path
再次调用render,生成一个新的虚拟DOM。
现在得到两个虚拟DOM。
循环递归运算,找出两个虚拟DOM的差异(找出最小的脏节点集合),通过一个队列更新,重新渲染DOM。
(9)when vm.$destroy() is called
当虚拟DOM被destroy()方法调用,路由切换的时候,组件会销毁。
(10)Teardown watchers, child components and event listeners
拆卸watchers、子组件,事件处理器解绑。

二、例子代码

<html>
<head><title>生命周期</title></head>
<body><div id="app"><h1 v-text="num"></h1><button @click="add">自增</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script><script>const app = new Vue({data() {return {num: 1}},beforeCreate() {console.log('---beforeCreate')},created() {console.log('---created')},beforeMount() {console.log('---beforeMount')},mounted() {console.log('---mounted')},beforeUpdate() {console.log('---beforeUpdate')},updated() {console.log('---updated')},beforeDestroy() {console.log('---beforeDestroy')},destroyed() {console.log('---destroyed')},methods: {add() {console.log('---add')this.num++}}})app.$mount('#app') // 挂载,相当于el选项</script></body>
</html>

说明:

钩子函数挂载在$options下面

http://www.xdnf.cn/news/822.html

相关文章:

  • 深度学习算法:从基础到实践
  • 第 28 场 蓝桥月赛
  • android framework开发的技能要求
  • HarmonyOS 笔记
  • Linux命令--将控制台的输入写入文件
  • Java编程基础(第三篇:初见静态方法)
  • 网络操作系统与应用服务器
  • Linux教程-Shell编程系列一
  • 算法—选择排序—js(场景:简单实现,不关心稳定性)
  • day1 python训练营
  • 嵌入式芯片中的 SRAM 内容细讲
  • JavaScript 一维数组转不含零的两个数
  • 专题十七:NAT技术
  • TS—抽象类
  • 英语学习4.15
  • Linux常见指令解析(二)
  • 坐标轴QCPAxis
  • 集成运放的关键技术参数
  • AutoSAR从概念到实践系列之MCAL篇(二)——Mcu模块配置及代码详解(上)
  • 20.3 使用技巧6
  • 【统计分析120】统计分析120题分享
  • 字节跳动发布UI-TARS-1.5,入门AI就来近屿智能
  • using用法整理
  • 海拔与大气压关系,大气压单位,气压传感器对比
  • RV1126网络环境TFTPNFS搭建(三)
  • 《Learning Langchain》阅读笔记4-基于 Gemini 的 Langchain:组装 LLM 应用的多个部分
  • 继承(2):
  • C语言基础
  • React 文章 分页
  • LACP协议解析