每个 Vue 实例在被创建时都要经过一系列的初始化过程。如需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。
一个 Vue 实例
我们创建一个 Vue 实例,并在每个阶段验证 Vue 的生命周期函数。
Vue 实例的生命周期函数并不放置在
methods里,而是单独放置在 Vue 的实例之中。
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Vue实例生命周期函数</title>
<script src='./vue.js'></script></head><body>
<div id="app"></div>
<script>
//生命周期函数就是Vue实例在某一个时间点会自动执行的函数
var vm = new Vue({ el: "#app", template: "<div>{{test}}</div>", data: { test: "hello world"
}, // Vue初始化
beforeCreate: function(){ console.log('beforeCreate')
}, created: function(){ console.log('created')
}, //页面渲染之前 挂载之前的时间点
beforeMount: function(){ console.log('beforeMount') console.log(this.$el)
}, // 挂载到页面之后
mounted: function(){ console.log('mounted') console.log(this.$el)
}, //当数据发生改变的时候 执行
beforeUpdate: function(){ console.log('beforeUpdate')
}, updated: function(){ console.log('updated')
}, // vm.$destroy()被called的时候触发
beforeDestroy: function(){ console.log('beforeDestroy')
}, destroyed: function(){ console.log('destroyed')
}
}) </script></body></html>生命周期函数
生命周期函数就是Vue实例在某一个时间点会自动执行的函数
Vue 初始化:
beforeCreate、created页面渲染之前:
beforeMount挂载到页面之后:
mounted
当数据发生改变时:
beforeDestroy(重新渲染之前) 、destroyed(重新渲染之后)
vm.$destroy()被调用时,即组件被销毁时:beforeDestroy、destroyed
生命周期图
下图展示了 Vue 实例的声明周期,结合上一节的示例,可以更好的理解 Vue 的这八个声明周期钩子。
其他
除此之外 Vue 还拥有 activated、deactivated 、errorCaptured 这三个生命周期钩子。
activated
当页面重新显示的时候,执行。搭配 keep-alive、localStrage 和临时变量做页面性能优化。
deactivated
当页面即将被隐藏或替换成其他页面时,执行。可以用来解绑在 activated 上绑定的全局事件。
作者:evenyao
链接:https://www.jianshu.com/p/c8a7306aa844
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦



