从创建到销毁的过程/vue生命周期/vue实例化的生命周期
三大阶段
1、挂载阶段:一进入页面 看到界面渲染的效果
2、更新阶段:修改数据 更新
3、销毁阶段/卸载阶段:关闭浏览器或者v-if=false 移除组件
生命周期方法/钩子函数
特点:
1、名字固定
2、自动调用
一、挂载阶段
第一步:找数据
1、beforeCreate()
数据初始化之前
特点:获取数据获取不到
场景:用的不多
2、***created()
数据初始化之后
特点:获取数据可以得到
场景:应用多 发送ajax请求
<template>
<div>{{name}}</div>
</template>
<script>
export default {
data() {
return {
name: "zs",
};
},
beforeCreate(){
console.log('beforeCreate '+this.name);
},
created(){
console.log('created '+this.name);
}
};
</script>
第二步:找模板
el template

第三步:渲染挂载

3、beforeMount()
挂载之前
特点:null DOM还没有挂载完成
场景:不多
4、mounted()
挂载之后
特点:DOM挂载完成
场景:应用多 发送ajax请求 操作DOM
<template>
<div>
<h1>我是h1</h1>
</div>
</template>
<script>
export default {
beforeMount() {
console.log("beforeMount", document.querySelector("h1"));
},
mounted() {
console.log("mounted", document.querySelector("h1"));
},
};
</script>
<style>
</style>

二、更新阶段
1、beforeUpdate()
数据更新前的数据
2、Updated()
数据更新后的数据
<template>
<div>
<h3>{{age}}</h3>
</div>
</template>
<script>
export default {
data() {
return {
age:9,
};
},
beforeUpdate(){
console.log('beforeUpdate'+document.querySelector('h3').innerHTML);
},
updated(){
console.log('updated'+document.querySelector('h3').innerHTML);
}
};
</script>
三、销毁阶段
1、beforeDestroy()
2、destroyed()
创建两个vue组件
App.vue
<template>
<div>
<Child v-if="isShow"></Child>
</div>
</template>
<script>
import Child from '@/Child'
export default {
components:{
Child,
},
data() {
return {
isShow:true
};
},
};
</script>
Child.vue
<template>
<div>
{{name}}
<h1>我是h1</h1>
<h3>{{age}}</h3>
</div>
</template>
<script>
export default {
data() {
return {
name: "zs",
age:9,
};
},
created(){
console.log('created '+this.name);
this.timeId=setInterval(function(){
console.log(8888);
},1000)
},
beforeDestroy(){
console.log('beforeDestroy');
clearInterval(this.timeId)
},
destroyed(){
console.log('destroyed');
}
};
</script>
<style>
</style>
本文详细探讨了Vue实例的生命周期,分为挂载、更新和销毁三个阶段,并重点解析了各阶段的钩子函数,如created、mounted、updated和destroyed等。在挂载阶段,强调了created和mounted在数据初始化和DOM操作上的应用场景;更新阶段讨论了数据更新前后的beforeUpdate和Updated钩子;最后介绍了组件销毁前后的beforeDestroy和destroyed。文章还提及了在不同阶段使用钩子函数进行AJAX请求和DOM操作的实际例子。
1122

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



