尚硅谷的vue旅程12-vue中的生命周期(部分原理、常用勾子和完整的生命周期展示)

简介

一.
	1.vue对象的生命周期
		1).初始化显示   (只执行一次)
			* beforeCreate()
			* created()
			* beforeMount()
			* mounted()
	
		2).更新显示 this.xxx = value   (执行n次)
			* beforeUpdate()
			* updated() 
		
		3).销毁死亡  this.$destroy()   (只执行一次)
			* beforeDestroy()
			* destroyed()
	
	2.常用的生命周期
			1.mounted():发送ajax请求,启动定时等异步任务
			2.beforeDestroy():做收尾工作,如:清除定时器

二.
	1.常用的勾子函数:mounted  befforeDestroy
	
	2.遇到回调函数(例如定时器中的function参数),用箭头函数来声明定义,这样会寻找其外部的this
	
	3.下列代码要实现的效果: ①每隔一段时间,进行显示或隐藏,可以使用mounted勾子
	  ②清除vue实例前,防止 内存泄漏问题(例子:vue势力被清除了,但是实例中的定时器还在运行),使用beforeDestroy勾子
		③生命周期完整展示

代码示例

<div id="test">
	<button @click="destroyVm">destroy vm</button>
	<p v-show="isShow">尚硅谷IT教育</p>
</div>	
	
<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>	
<script>
	new Vue({
		el:"#test",
		data (){
			return {
				isShow:true
			}
		},
		// 1).初始化显示 
		beforeCreate(){
			console.log("beforeCreate()");
		},
		created(){
			console.log("created()")
		},
		beforeMount(){
			console.log("beforeMount()");
		},
		mounted(){ //初始化显示后,立即调用(一次)
			console.log("mounted()");
			//每隔一端固定时间,隐藏显示
			this.intervalId = setInterval(() => {  //遇到回调函数,用箭头函数来声明定义,这样会寻找其外部的this
				console.log("定时器正在运行");//Console后台还在运行,用beforeDestroy函数来来进行删除定时器
				this.isShow = !this.isShow;
			},1000)
		},
		
		// 2).更新显示 this.xxx = value   (执行n次)
		beforeUpdate(){
			console.log("beforeUpdate()");
		},
		updated(){
			console.log("updated()");
		},
		
		// 3).销毁死亡  this.$destroy()   (只执行一次)
		beforeDestroy(){  //在vue实例被销毁之前,执行一次
			console.log("beforeDestroy()");
			clearInterval(this.intervalId);
		},
		destroyed(){
			console.log("destroyed()");
		},
		
		methods:{
			destroyVm(){
				this.$destroy();//销毁当前的vue实例,此时定时器还在运行,(内存泄露)
			}
		}
	})
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值