今年这个年关过的紧张兮兮,疫情肆虐,咱蜗居就是为国家做贡献啦...
既然不能出门,那只有打开电脑,学习使我快乐了.../(ㄒoㄒ)/~~
最近正在学习前台框架vue,边学边笔记,也和大家一起分享一下
觉得生命周期这一块还是挺重要的,而且对于我个人而言还是比较容易忽视的,做个笔记记录一下,嘿嘿
下图展示了实例的生命周期:
vue的生命周期分三个阶段:初始化显示、更新显示、死亡;
初始化显示阶段又可分为四个小阶段:beforCreate,created,beforeMount,mounted(挂载:初始化显示之后立即调用)
更新显示阶段也分为两个小阶段:beforeUpdate,updated
死亡阶段也分为两个小阶段:beforeDestory,destoryed
每个生命阶段都对应相应的回调函数,也可以叫勾子函数;
- 初始化显示
- beforeCreate()
- created()
- beforeMount()
- mounted()
- 更新状态: this.xxx = value
- beforeUpdate()
- updated()
- 销毁 vue 实例: vm.$destory()
- beforeDestory()
- destoryed
vue创建函数时用箭头创建匿名函数=>,会自带this,如果内部没有会调用外部的this,外部的this就是vm对象
常用的生命周期方法
- created()/mounted(): 发送 ajax 请求, 启动定时器等异步任务
- beforeDestory(): 做收尾工作, 如: 清除定
编码示例:
<div>
<button @click="destoryVue">destory vue</button>
<p v-show="isShowing">{{msg}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
var vue = new Vue({
el: 'div',
data: {
msg: '明明在学JAVA',
isShowing: true,
persons: []
},
beforeCreate () {
console.log('beforeCreate() msg=' + this.msg)},
created () {
console.log('created() msg='+this.msg)
this.intervalId = setInterval(() => {
console.log('-----')
this.isShowing = !this.isShowing
}, 1000)
},
beforeMount () {
console.log('beforeMount() msg='+this.msg)
},
mounted () {
console.log('mounted() msg='+this.msg)
},
beforeUpdate() {
console.log('beforeUpdate isShowing='+this.isShowing)
},
updated () {
console.log('updated isShowing='+this.isShowing)
},
beforeDestroy () {
console.log('beforeDestroy() msg='+this.msg)
clearInterval(this.intervalId)
},
destroyed () {
console.log('destroyed() msg='+this.msg)
},
methods: {
destoryVue () {
vue.$destroy()
}
}
})
</script>