Vue的生命周期执行顺序
分别有一下几种: beforeCreate(创建前),created(创建后),beforeMount(挂载前),mounted(挂载后), beforeUpdate(更新前),updated(更新后),beforeDestroy(销毁前),destroyed(销毁后)
子:
<template>
<div>
<ul id="myUl">
<li v-for="(item, ind) in arr" :key="ind">{{ item }}</li>
</ul>
<button @click="arr.push(Math.random() * 10)">增加一个元素</button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "我是变量",
arr: [1, 2, 3, 4],
isShow: true,
}
},
beforeCreate() {
// 1. 创建前
console.log("子beforeCreate")
},
created() {
// 2. 创建后=> 发送ajax请求
console.log("子created")
},
beforeMount() {
// 3. 挂载前
console.log("子beforeMount")
},
mounted() {
// 4. 挂载后=> 操作dom
console.log("子mounted")
// console.log(document.getElementById("myUl").children[1].innerHTML)
},
beforeUpdate() {
// 5. 更新前
console.log("子beforeUpdate")
// 比如点击新增数组元素, vue会触发此生命周期函数, 但是此时页面并未更新, 所以获取不到新增的li标签
// console.log(document.getElementById("myUl").children[4].innerHTML) // 报错
},
updated() {
// 6. 更新后
console.log("子updated")
},
beforeDestroy() {
// 7. 销毁前
// (清除定时器 / 解绑js定义的事件)
console.log("子beforeDestroy")
},
destroyed() {
// 8. 销毁后
// (清除定时器 / 解绑js定义的事件)
console.log("子destroyed")
},
};
</script>
<style>
</style>
父:
<template>
<smzq></smzq>
</template>
<script>
import smzq from "./生命周期.vue";
export default {
data() {
return {
msg: "我是变量",
arr: [1, 2, 3, 4],
isShow: true,
}
},
components: { smzq },
beforeCreate() {
// 1. 创建前
console.log("父beforeCreate")
},
created() {
// 2. 创建后=> 发送ajax请求
console.log("父created")
},
beforeMount() {
// 3. 挂载前
console.log("父beforeMount")
},
mounted() {
// 4. 挂载后=> 操作dom
console.log("父mounted")
},
beforeUpdate() {
// 5. 更新前
console.log("父beforeUpdate")
// 比如点击新增数组元素, vue会触发此生命周期函数, 但是此时页面并未更新, 所以获取不到新增的li标签
// console.log(document.getElementById("myUl").children[4].innerHTML) // 报错
},
updated() {
// 6. 更新后
console.log("父updated")
},
beforeDestroy() {
// 7. 销毁前
// (清除定时器 / 解绑js定义的事件)
console.log("父beforeDestroy")
},
destroyed() {
// 8. 销毁后
// (清除定时器 / 解绑js定义的事件)
console.log("父destroyed")
},
};
</script>
<style>
</style>
效果: