对Vue生命周期的一些简单见解
文章目录
- 前言
- 一、甚麽是[Vue的生命周期]?
- 二、生命周期函数
- 1.beforeCreate
- 2.created
- 3.beforeMount
- 4.mounted
- 5.beforeDestory
- 6.destoryed
- 7.beforeUpdate
- 8.updated
- 三、Vue的一生要做些甚麽?
- 1.Vue对象创立,Vue出生。
- 2.初始化
- 2.5BeforeCreated函数调用
- 3.继续初始化
- 3.5Create函数调用
- 4.判断el是否挂载了DOM
- 5.判断是否有模板
- 5.5beforeMount函数调用
- 5.6前面生成的render函数被调用
- 6.虚拟el创建,DOM替换
- 6.5.DOM树渲染至页面完毕
- 7.Mounted函数调用。
- 8.准备完毕Mounted状态
- 9.Vue实例被请求销毁
- 9.5BeforeDestory函数调用
- 10.清除各Vue组件
- 11.组件销毁完毕
- 12.Destory函数调用
- 总结
前言
升学,找工作,失业,找工作,买房,成家,一些人甚至至死都没能跑完这条人生的长路,他们的一生在奔波中度过,却不曾看到过一丝沿途的风景。
Vue是一个这样的人,在他短暂而被安排的明明白白的人生路途中,只剩下奔波,沿途的风景未能让他驻足一瞬,他创造的诸多美好,却从无法看哪怕是一眼。 狗头)
一、甚麽是[Vue的生命周期]?
Vue的每个组件都是独立的,正因如此,Vue的每个组件也都有各自的生命周期(就像人的肺和肾都有自己的寿命),他们共同组成了[Vue的生命周期]。
Vue并不像人的生命周期一样有生老病死,如果Vue对象不被销毁,Vue会一直在那里,所以“生命周期”这个词在此处大可不必完全解读为“生命周期”原本的意思,知道是Vue创立后固定要做的那么些事儿就好了。
二、生命周期函数
有时我们需要在Vue执行到某一步时,执行某些操作,那么可以利用这些生命周期函数来完成,把要执行的命令写进这些生命周期函数里,在Vue执行到这些函数的所在时,就会顺带完成你需要的操作,而我们首先要知道这些周期函数在什么时候会被执行、他们都是哪些。
1.beforeCreate
在示例初始化、data observer配置和事件配置完成之间调用
2.created
初始化依赖和注入,data初始化完毕,计算属性和event/watch事件进行回调后,DOM树挂载前。
通常会在此处进行一部分网络请求。
3.beforeMount
挂载前,创建虚拟el前,生成模板template后。
4.mounted
挂载完成,DOM树渲染完毕后。
5.beforeDestory
Vue实例销毁前。
6.destoryed
Vue所有子组件销毁后。
7.beforeUpdate
数据data有更新,已被调用后。
8.updated
虚拟DOM重新渲染发生变化的数据。
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {const vm: Component = thisconst prevEl = vm.$elconst prevVnode = vm._vnodeconst restoreActiveInstance = setActiveInstance(vm)vm._vnode = vnode// Vue.prototype.__patch__ is injected in entry points// based on the rendering backend used.if (!prevVnode) {// initial rendervm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)} else {// updatesvm.$el = vm.__patch__(prevVnode, vnode)}restoreActiveInstance()// update __vue__ referenceif (prevEl) {prevEl.__vue__ = null}if (vm.$el) {vm.$el.__vue__ = vm}// if parent is an HOC, update its $el as wellif (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {vm.$parent.$el = vm.$el}// updated hook is called by the scheduler to ensure that children are// updated in a parent's updated hook.}
三、Vue的一生要做些甚麽?
1.Vue对象创立,Vue出生。
构造函数生成Vue实例;
new Vue();
2.初始化
原步骤Init Event&Lifecycle;
初始化事件相关:Event;
初始化各生命周期函数:Lifecycle(也叫钩子函数);
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
//src/core/instance/lifecycle.js
export function initLifecycle(vm: Component) {const options = vm.$options// locate first non-abstract parentlet parent = options.parentif (parent && !options.abstract) {while (parent.$options.abstract && parent.$parent) {parent = parent.$parent}parent.$children.push(vm)}vm.$parent = parentvm.$root = parent ? parent.$root : vmvm.$children = []vm.$refs = {}vm._watcher = nullvm._inactive = nullvm._directInactive = falsevm._isMounted = falsevm._isDestroyed = falsevm._isBeingDestroyed = false
}
以上为对生命周期函数lifecycle的初始化
//src/coreinstance/event.js
export function initEvents (vm: Component) {vm._events = Object.create(null)vm._hasHookEvent = false// init parent attached eventsconst listeners = vm.$options._parentListenersif (listeners) {updateComponentListeners(vm, listeners)}
}
以上为对事件Event的初始化
export function callHook(vm: Component, hook: string) {// #7573 disable dep collection when invoking lifecycle hookspushTarget()const handlers = vm.$options[hook]const info = `${hook} hook`if (handlers) {for (let i = 0, j = handlers.length; i < j; i++) {invokeWithErrorHandling(handlers[i], vm, null, vm, info)}}if (vm._hasHookEvent) {vm.$emit('hook:' + hook)}popTarget()
}
以上为调用钩子函数Hook
2.5BeforeCreated函数调用
生命周期函数BeforeCreated被调用。
//src/core/instance/init.jscallHook(vm, 'beforeCreate')
3.继续初始化
原步骤Init injections & reactivity & state
初始化依赖提供:provide;
初始化依赖注入:injections;
初始化Vue响应式的核心:reactivity ;
provide提供依赖,提供的依赖可以是一个对象,或者是一个能返回对象的函数。依赖内包含了属性和属性值,属性值可以是一个对象。
injections 注入依赖,在后代组件里使用 inject 选项来为其注入需要添加在这个实例上的属性,包含from和default默认值。
reactivity系列是Vue响应式的核心。
需要调用以上函数
//src/core/instance/inject.js
export function initProvide (vm: Component) {const provide = vm.$options.provideif (provide) {vm._provided = typeof provide === 'function'? provide.call(vm): provide}
}export function initInjections (vm: Component) {const result = resolveInject(vm.$options.inject, vm)if (result) {toggleObserving(false)Object.keys(result).forEach(key => {/* istanbul ignore else */if (process.env.NODE_ENV !== 'production') {defineReactive(vm, key, result[key], () => {warn(`Avoid mutating an injected value directly since the changes will be ` +`overwritten whenever the provided component re-renders. ` +`injection being mutated: "${key}"`,vm)})} else {defineReactive(vm, key, result[key])}})toggleObserving(true)}
}
以上为初始化依赖提供provide与依赖注入injections
//src/core/instance/state.js
export function initState (vm: Component) {vm._watchers = []const opts = vm.$optionsif (opts.props) initProps(vm, opts.props)if (opts.methods) initMethods(vm, opts.methods)if (opts.data) {initData(vm)} else {observe(vm._data = {}, true /* asRootData */)}if (opts.computed) initComputed(vm, opts.computed)if (opts.watch && opts.watch !== nativeWatch) {initWatch(vm, opts.watch)}
}
以上为初始化state
3.5Create函数调用
生命周期函数Create被调用。
此段出自Vue源码文件"init.js"
4.判断el是否挂载了DOM
没有挂载就挂载一个。
有就直接下一步。
watch事件回调
this._init末的$mount函数运作。
//src/platform/web/runtime/index.js
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {el = el && inBrowser ? query(el) : undefinedreturn mountComponent(this, el, hydrating)
}
以上为$mount函数的基本模型
//src/platform/web/entry-runtime-with-compiler.js
Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean
): Component {el = el && query(el)/* istanbul ignore if */if (el === document.body || el === document.documentElement) {process.env.NODE_ENV !== 'production' && warn(`Do not mount Vue to <html> or <body> - mount to normal elements instead.`)return this}
以上为Vue中的$mount函数被调用
Vue.prototype.$watch = function (expOrFn: string | Function,cb: any,options?: Object): Function {const vm: Component = thisif (isPlainObject(cb)) {return createWatcher(vm, expOrFn, cb, options)}options = options || {}options.user = trueconst watcher = new Watcher(vm, expOrFn, cb, options)if (options.immediate) {try {cb.call(vm, watcher.value)} catch (error) {handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)}}return function unwatchFn () {watcher.teardown()}}
$watch被调用
5.判断是否有模板
模板template作为模板占位符,用来包裹HTML元素,其不会被渲染到页面上,可以有三种写法:作为option属性写在Vue对象里、直接作为HTML标签、写在script标签里(第三个官方推荐写法,为script标签里的type属性赋值"x-template")。
有template模板
把模板template转换为render函数(render函数会在后续渲染DOM中发挥作用)。
无template模板
将el挂载的对象的外层HTML作为模板template。
没有对象就new一个啊(不是)
this._init末的$mount函数运作完毕。
//src/platform/web/entry-runtime-with-compiler.jsconst options = this.$options// resolve template/el and convert to render functionif (!options.render) {let template = options.templateif (template) {if (typeof template === 'string') {if (template.charAt(0) === '#') {template = idToTemplate(template)/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && !template) {warn(`Template element not found or is empty: ${options.template}`,this)}}} else if (template.nodeType) {template = template.innerHTML} else {if (process.env.NODE_ENV !== 'production') {warn('invalid template option:' + template, this)}return this}} else if (el) {template = getOuterHTML(el)}if (template) {/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {mark('compile')}const { render, staticRenderFns } = compileToFunctions(template, {outputSourceRange: process.env.NODE_ENV !== 'production',shouldDecodeNewlines,shouldDecodeNewlinesForHref,delimiters: options.delimiters,comments: options.comments}, this)options.render = renderoptions.staticRenderFns = staticRenderFns/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {mark('compile end')measure(`vue ${this._name} compile`, 'compile', 'compile end')}}}return mount.call(this, el, hydrating)
}
判断是否具有模板template,若是无模板template就将外层HTML转换为template;
5.5beforeMount函数调用
生命周期函数beforeMount被调用。
5.6前面生成的render函数被调用
render函数被调用来生成虚拟DOM,虚拟DOM是渲染好的。
Vue.prototype._render = function (): VNode {const vm: Component = thisconst { render, _parentVnode } = vm.$optionsif (_parentVnode) {vm.$scopedSlots = normalizeScopedSlots(_parentVnode.data.scopedSlots,vm.$slots)}// set parent vnode. this allows render functions to have access// to the data on the placeholder node.vm.$vnode = _parentVnode// render selflet vnodetry {vnode = render.call(vm._renderProxy, vm.$createElement)} catch (e) {handleError(e, vm, `render`)// return error render result,// or previous vnode to prevent render error causing blank component/* istanbul ignore else */if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {try {vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)} catch (e) {handleError(e, vm, `renderError`)vnode = vm._vnode}} else {vnode = vm._vnode}}// if the returned array contains only a single node, allow itif (Array.isArray(vnode) && vnode.length === 1) {vnode = vnode[0]}// return empty vnode in case the render function errored outif (!(vnode instanceof VNode)) {if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {warn('Multiple root nodes returned from render function. Render function ' +'should return a single root node.',vm)}vnode = createEmptyVNode()}// set parentvnode.parent = _parentVnodereturn vnode}
以上为对render函数的调用
6.虚拟el创建,DOM替换
原步骤Create vm $el and replace “el” with it.
Vue实例下的虚拟el创建,虚拟DOM替换原本的DOM。
-render方法在此处运作生成虚拟DOM对象。
6.5.DOM树渲染至页面完毕
虚拟DOM挂载完毕,DOM树已经成功渲染至页面,页面已经具有样式,可以进行正常DOM操作。
7.Mounted函数调用。
生命周期函数Mounted调用。
8.准备完毕Mounted状态
如果在这个状态出现了数据更新需要再次渲染来更新页面:
生命周期函数BeforeUpdate调用;
虚拟DOM重新渲染,但仅以最小的DOM开支渲染发生变化的部分,其他部分复用,节省工作量。
9.Vue实例被请求销毁
9.5BeforeDestory函数调用
生命周期函数BeforeDestory调用。
10.清除各Vue组件
清除watchers、child子组件、components和eventlistener事件监听 等等…
Vue.prototype.$destroy = function () {const vm: Component = thisif (vm._isBeingDestroyed) {return}callHook(vm, 'beforeDestroy')vm._isBeingDestroyed = true// remove self from parentconst parent = vm.$parentif (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {remove(parent.$children, vm)}// teardown watchersif (vm._watcher) {vm._watcher.teardown()}let i = vm._watchers.lengthwhile (i--) {vm._watchers[i].teardown()}// remove reference from data ob// frozen object may not have observer.if (vm._data.__ob__) {vm._data.__ob__.vmCount--}// call the last hook...vm._isDestroyed = true// invoke destroy hooks on current rendered treevm.__patch__(vm._vnode, null)// fire destroyed hookcallHook(vm, 'destroyed')// turn off all instance listeners.vm.$off()// remove __vue__ referenceif (vm.$el) {vm.$el.__vue__ = null}// release circular reference (#6759)if (vm.$vnode) {vm.$vnode.parent = null}}
}
$destory清除实例里的方法
11.组件销毁完毕
12.Destory函数调用
生命周期函数Destory调用。
至此Vue的一段生命周期便执行完成,它完成了它的使命,暂时。
总结
今天先告一段落…
终于考完试了!打算下面几天都拿来肝文了!
已经加入一些Vue源码片段来展示各个生命周期函数:~),我依然在完善这篇文章,部分代码尚未找到,所以后续还会有增加…
对Vue生命周期的一些简单见解相关推荐
- vue 生命周期_Vue生命周期小白看了都会的
最近一直在学习Vue,而vue生命周期是我们不可能绕开的一个很核心的知识点,今天来简单的梳理一下大概的内容. 一.钩子函数 在一开始学习的时候,总有钩子函数这个名词冒出来,而且在vue官网文档中也频繁 ...
- 1.vue生命周期详解(2020.12.05)
vue生命周期,直接上官方图 补一下引用vue的链接( src = "https://cdn.bootcss.com/vue/2.4.2/vue.js) 要明确生命周期,我们必须从钩子下手: ...
- Vue生命周期(个人理解)
描述:今天进度到生命周期 other-teacher只讲了两个项目使用到的生命周期 剩下的自己扩展,哎,自己来了兴趣,为啥,自己第一次面试的时候记得很清楚.面试官:"简单说一下你对vue生命 ...
- vue 生命周期的详解
一.vue生命周期的解析 > 1>什么是vue生命周期 每个vue实例在被创建之前都要经过一系列的初始化过程,这个过程就是vue的生命周期.详细来说,就是Vue实例从开始创建,初始化数据, ...
- Vue生命周期及钩子
一.前言 Vue是一个专注于视图层的一个响应式的前端框架,而且使用起来特别简单.灵活以及横向扩展性极高,跨平台,目前也广受前端开发人员以及企业的喜爱,从某种程度上能够达到高效率开发生产 二.Vue中的 ...
- Vue生命周期详解图
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 一.什么是vue的生命周期? 二.vue生命周期分几部分?并都做了什么? 三.vue知识补充 四.vue生命周期图解 一.什 ...
- Vue生命周期及各组件间的执行情况
文章目录 前言 一.Vue的生命周期是什么? 二.Vue生命周期中具体过程 1.Vue生命周期中的函数 创建Vue实例期阶段: 运行阶段: 销毁阶段: 2.加入keep-alive后 1)keep-a ...
- vue生命周期钩子函数的正确使用方式
对于vue生命周期我们还是要先了解清楚,因为不同的生命期用不同的钩子函数,先上图: 遇到的一个问题 在我的项目中,常用的生命周期钩子函数一直都是mounted,对于大部分情况,都是屡试不爽.捷报频传~ ...
- Vue生命周期钩子函数的使用以及应用场景
文章目录 前言 钩子函数介绍 beforeCreate(创建前) created(创建后) beforeMounted(挂载前) mounted(挂载后) beforeUpdate(更新前) upda ...
最新文章
- 2022-2028年中国软件测试行业市场研究及前瞻分析报告
- combo:机器学习模型合并工具库
- 在mac操作系统下,Intellij IDEA默认jdk版本的修改
- “举报”阿里巴巴 Arthas,大幅降低 OOM Trouble shooting 门槛
- php 字符串 中文位置,怎样查找中文字符的位置呢
- ios php rsa,RSA 加密 iOS
- 产生复选框的html,html根据复选框勾选顺序生成字符串
- 专利计算机存储介质是智力活动,涉及计算机程序的发明专利申请的相关问题PPT课件.pptx...
- python爬虫爬商品库存_利用Python爬虫爬取指定天猫店铺全店商品信息
- shiro 升级_小米11消息再次确认:骁龙875有独占期,超广角镜头大升级
- HDU-3072-IntelligenceSystem(tarjan,贪心)
- 将java对象转换成json字符串_将java对象转换成json字符串
- html5都能干嘛种花,把这19种花种起来,整个家都能变成大花园!
- 【全国第二批】供应链创新与应用示范企业和示范城市申报材料条件内容认定好处费用时间
- 有哪些既实用又好看的蓝牙耳机?高颜值实用蓝牙耳机排行
- 网页自动填表html,WebBrowser1.HtmlInput 实现浏览器文本自动填写与点击
- Linux 进行yum 安装是出现文件 conflicts 解决方法
- 11 02 11 无用功
- 求3000以内的亲密数C语言
- C函数库(libc、glibc、uClibc、newlib)