以下生命周期是vue2.x 一共有11个 常用的有8个
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed
activated
deactivated
errorCaptured
总结:
vue生命周期整体分为四大阶段
创建 create
创建前
创建后
挂载 mount
挂载前
挂载后
更新 update
更新前
更新后
销毁 destroy
销毁前
销毁后
每一个组件都有属于自己的完整的生命周期
每个组件之间的生命周期互不影响
每个组件内部的生命周期是有先后顺序的 跟编写的先后顺序没有任何的关系
想要调用销毁生命周期
我们可以使用 $destroy()方法或者使用v-if
生命周期中
beforeCreate不能获取到data数据
created和mounted一般用于数据的动态请求及赋值
updated和beforUpdate只会在数据改变的时候触发
destroyed和beforDestroy一般用于组件的销毁 一般用于定时器的销毁
注意:
后期写项目我们可能使用最多的是created或者mounted
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>{{m}}</p>
<child v-if="show"></child>
</div>
</body>
<script src="vue.min.js"></script>
<script>
Vue.component('child', {
data() {
return {
msg: 123
}
},
template: `
<div class="child">child</div>
`,
updated() {
console.log("child更新后")
},
beforeDestroy() {
console.log("child销毁前")
},
destroyed() {
console.log("child销毁后")
},
beforeCreate() {
console.log("child创建前", this.msg)
},
created() {
console.log("child创建后")
},
beforeMount() {
console.log("child挂载前")
},
mounted() {
console.log("child挂载后")
},
beforeUpdate() {
console.log("child更新前")
}
})
var app = new Vue({
el: "#app",
data: {
m: 100,
show: true,
time: null
},
beforeMount() {
console.log("挂载前")
},
mounted() {
console.log("挂载后")
},
beforeUpdate() {
console.log("更新前")
},
updated() {
console.log("更新后")
},
beforeDestroy() {
console.log("销毁前")
},
destroyed() {
console.log("销毁后")
clearInterval(this.time)
},
beforeCreate() {
console.log("创建前", this.m)
},
created() {
console.log("创建后", this.m)
this.time = setInterval(() => {
console.log(1)
}, 1000)
}
})
</script>
</html>