vue生命周期

Vue实例在创建、更新和销毁时经历多个生命周期钩子,包括beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeDestroy和destroyed。这些钩子提供了在不同阶段插入自定义代码的机会。在实际应用中,created和mounted常用于发起ajax请求和异步任务,而beforeDestroy则用于清理资源,如停止定时器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。

生命周期图示:
在这里插入图片描述
1vue对象生命周期
1)初始化显示
* beforeCreate()
* created()
* beforeMount()
* mounted()
2)更新显示:this.xxx=value
* beforeUpdate()
* updated()
3)销毁vue实例:vm.$destroy()
*beforeDestroy()
*destroyed()
2.常用的生命周期方法
created()/mounted(): 发送ajax请求,启动定时器等异步任务
beforeDestroy(): 做收尾工作,如:清除定时器

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="test">
			<button type="button" @click="destroyVM">destroy vm</button>
			<p v-show="isShow">何桥是一只猪</p>
			{{isShow}}
		</div>
		<script type="text/javascript">
			new Vue({
				el:'#test',
				data:{
					isShow: false,
				},
				//1初始阶段
			    beforeCreate() {
			    	console.log('beforeCreate');
			    },
				created() {
					console.log('created');
				},
				beforeMount() {
					console.log('beforeMount');
				},
				mounted(){//初始化 后立即调用(1c次
				    console.log('mounted');
				    this.intervalId = setInterval(() => {//函数作为参数传递,用箭头函数(函数内部没有自己的this))
					
						this.isShow = !this.isShow
					}, 1000)
					
				},
				
				//2更新阶段
				beforeUpdate() {
					console.log('beforeUpdate')
				},
				updated() {
					console.log('updated')
				},			
				
				//3死亡阶段
				beforeDestroy(){//死亡之前调用(1次)
				    console.log('beforeDeatroy');
					//清除定时器
					clearInterval(this.intervalId);
				},
				destroyed() {
					console.log('destroyed')
				},
				
				
				methods:{
					destroyVM(){
						//干掉VM
						this.$destroy() 
					}
				}
				
			})
		</script>
	</body>
</html>

注意:
不要在选项属性或回调上使用箭头函数,比如 created: () => console.log(this.a) 或 vm.$watch(‘a’, newValue => this.myMethod())。因为箭头函数并没有 this,this 会作为变量一直向上级词法作用域查找,直至找到为止,经常导致 Uncaught TypeError: Cannot read property of undefined 或 Uncaught TypeError: this.myMethod is not a function 之类的错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值