web前端-初探Vue生命周期
【摘要】 一、vue的生命周期是什么 vue每个组件都是独立的,每个组件都有一个属于它的生命周期,从一个组件创建、数据初始化、挂载、更新、销毁,这就是一个组件所谓的生命周期。,首先看一张图吧,这是官方文档上的图片,图中可以看到在组件中具体的方法有:vm创建:new Vue()初始化显示:beforeCreate()----created()---beforeMount()---mounted()...
一、vue的生命周期是什么
vue每个组件都是独立的,每个组件都有一个属于它的生命周期,从一个组件创建、数据初始化、挂载、更新、销毁,这就是一个组件所谓的生命周期。
,首先看一张图吧,这是官方文档上的图片,图中可以看到在组件中具体的方法有:
vm创建:new Vue()
初始化显示:beforeCreate()----created()---beforeMount()---mounted() 到此初始化结束
更新显示:beforeUpdate()---updated() 数据更新
上一波代码,console查看:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>10</title>
</head>
<body>
<div id="app">
<h1>{{message}}</h1>
<button @click="destroyVm">destroy vm</button>
<p v-show="isShow">生命周期</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el:"#app",
data:{
message:'vue生命周期',
isShow:true
},
//初始化阶段
beforeCreate(){
console.log('beforeCreate()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
},
created(){
console.log('created()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
},
beforeMount(){
console.log('beforeMount()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
},
mounted(){//初始化显示后立即调用(一次)
console.log('mounted()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
this.intervalId=setInterval(()=>{//用箭头函数可以保证this是外部的对象
console.log("-----")
this.isShow=!this.isShow
},1000)
},
//更新阶段
beforeUpdate(){
console.log('beforeUpdate()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
},
updated(){
console.log('updated()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
},
//死亡阶段
beforeDestroy(){//死亡之前调用(一次)
console.log('beforeDestroy()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
clearInterval(this.intervalId)//清除定时器
},
destroyed(){
console.log('destroyed()')
console.log("el :"+this.$el)
console.log("data :"+this.$data)
console.log("message :"+this.message)
},
methods:{
destroyVm(){
this.$destroy()//销毁vm
}
}
})
</script>
</body>
</html>
下面分析各个阶段调用生命周期的函数:
1.beforeCreate()进行初始化事件,进行数据观测,可以看到在created()的时候数据已经和data属性进行绑定,注意此时还没有el选项
2.到beforeMount()阶段,el选项已被挂载
3.由于设置了定时器,每一秒后data中的isShow变量会改变,即先后调用了beforeUpdate()和updated()函数
4.beforeDestroy():收尾工作,如清除定时器,在这一步,实例任然完全可用
5.destroyed():调用后,Vue实例指示的所有东西会解绑定,所有事件监听器会被移除,页面上的所有组件都不再变化了。
总结:vue 的生命周期,总得来说就是实例的创建和销毁这段时间的一个机制,也是vue框架的数据间的交互通信,弄清楚了它的各个阶段对以后的开发大有帮助
最后,天道酬勤,加油!
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)