首页> 基础笔记 >Vue学习笔记 Vue学习笔记

vue组件生面周期--父子组件执行顺序

作者:小萝卜 2024-03-19 浏览 101

简介父beforeCreate -> 父created -> 父beforeMount -> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted->父beforeUpdate->子beforeUpdate->子updated->父updated->父beforeDestroy->子beforeDestroy->子destroyed->父destroyed

父子组件执行顺序

父组件代码:

<template>

	<div>

		<input type="text" name="text" id="" v-model="text" />

		<button id="destroy" @click="handle">点击</button>

		<livechidren :text="text"></livechidren>

	</div>

</template>

<script>

import livechidren from "./livechidren.vue";

export default {
	components: { livechidren },
	data() {
		return {
			text: "",
		};
	},
	methods: {
		handle() {
			this.$destroy();
		},
	},
	beforeCreate() {
		console.log("父组件————beforeCreate...");
	},
	created() {
		console.log("父组件————create...");
	},
	beforeMount() {
		console.log("父组件————beforeMount...");
	},
	mounted() {
		console.log("父组件————mounted...");
	},
	beforeUpdate() {
		console.log("父组件————beforeUpdate...");
	},
	updated() {
		console.log("父组件————updated...");
	},
	beforeDestroy() {
		console.log("父组件————beforeDestroy...");
	},
	destroyed() {
		console.log("父组件————destroyed...");
	},
};
</script>

子组件代码:

<template>
	<div>{{text}}</div>
</template>

<script>
export default {
	data() {
		return {};
	},
	props:{
		text: {
			type: String,
		}
	},
	beforeCreate() {
		console.log("子组件————beforeCreate...");
	},
	created() {
		console.log("子组件————create...");
	},
	beforeMount() {
		console.log("子组件————beforeMount...");
	},
	mounted() {
		console.log("子组件————mounted...");
	},
	beforeUpdate() {
		console.log("子组件————beforeUpdate...");
	},
	updated() {
		console.log("子组件————updated...");
	},
	beforeDestroy() {
		console.log("子组件————beforeDestroy...");
	},
	destroyed() {
		console.log("子组件————destroyed...");
	},
};
</script>

执行结果:

父子组件生命周期执行顺序:

父beforeCreate -> 父created -> 父beforeMount -> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted->父beforeUpdate->子beforeUpdate->子updated->父updated->父beforeDestroy->子beforeDestroy->子destroyed->父destroyed

总结

1. 生命周期函数又名:生命周期回调函数、生命周期函数、生命周期钩子。

2. 生命周期函数是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。

3. 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。

4.生命周期函数中的this指向是vm 或 组件实例对象。

常用的生命周期钩子:

1.mounted: 发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】。

2.beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】。

很赞哦! (0)

相关文章

文章评论

    高端网站建设