生命周期:即在生命的某一个时刻,自动执行的函数
vue的生命周期有:
-
beforeCreate() 在实例创建之前,自动执行的函数
-
creater() 在实例创建之后,自动执行的函数
-
beforeMount() 在dom挂载之前,自动执行的函数
-
mounted() 在dom挂载完成之后,自动执行的函数 (在此之前都获取不到dom节点)
-
beforeUpdate() 在data中的数据有变化时,自动执行的函数
-
updated() 在data中的数据发生改变,页面中心渲染完成之后,自动执行的函数
-
beforeUnmount() 在实例销毁时,自动执行的函数
-
unmounted() 在实例销毁时,且dom完全销毁之后,自动执行的函数

代码提现:
<template>
<!-- 生命周期函数学习 -->
<div class="base01">
<home-back></home-back>
<div id="life">{{message}}</div>
<div class="btn" @click="bindChange">点击改变message</div>
</div>
</template>
<script>
import Back from "@/components/common/back.vue"
export default {
data(){
return {
message:'生命周期'
}
},
components:{
'home-back':Back
},
beforeCreate(){ // 在实例创建之前,自动执行的函数
console.log("beforeCreate")
console.log(document.getElementById('life'))
},
created(){ // 在实例创建之后,自动执行的函数
console.log("created")
console.log(document.getElementById('life'))
},
beforeMount(){ // 在dom挂载之前,自动执行的函数
console.log("beforeMount")
console.log(document.getElementById('life'))
},
mounted(){ // 在dom挂载完成之后,自动执行的函数
console.log("mounted")
console.log(document.getElementById('life'))
},
beforeUpdate(){ // 在data中的数据有变化时,自动执行的函数
console.log("beforeUpdate")
console.log(document.getElementById('life').innerHTML)
},
updated(){ // 在data中的数据发生改变,页面中心渲染完成之后,自动执行的函数
console.log("updated")
console.log(document.getElementById('life').innerHTML)
},
beforeUnmount() { // 在实例销毁时,自动执行的函数
console.log("updated")
},
unmounted() { // 在实例销毁时,且dom完全销毁之后,自动执行的函数
console.log("unmounted")
},
methods: {
bindChange(){
this.message = this.message=='生命周期'?"生命周期学习":"生命周期"
},
},
}
</script>
<style scoped lang="stylus">
.base01
font-size 25px
margin 40px 0 0 50px
.btn
cursor pointer
margin-top 20px
</style>

本文详细介绍了Vue.js组件的生命周期,包括beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeUnmount和unmounted等阶段,并通过代码示例展示了在各个阶段中如何操作。重点讲解了在不同生命周期钩子中对DOM的操作和数据更新的时机。
2747

被折叠的 条评论
为什么被折叠?



