1、组件生命周期:组件从创建到销毁的过程。
在这个过程中的不同阶段,vue会调用指定的组件方法
基本生命周期函数的四个阶段:
每一个阶段都对应着 之前
和 之后
两个函数,
之前
的函数使用较少,之后
的函数使用较多一些
- (1)
创建阶段
–>beforeCreate()、created() - (2)
挂载阶段
–>beforeMount()、mounted() - (3)
更新阶段
–>beforeUpdate()、updated() - (4)
卸载阶段
–>beforeDestroy()、destroyed()
这8个函数都是可选项,实际使用中,用到哪些就添加哪些
App.vue
<template>
<div id="app">
<!-- 添加单击事件,每次点击按钮后,数据发生改变,触发更新阶段的两个方法:
beforeUpdate()与Updated() -->
<button @click="n++">{
{
n}}</button>
<button @click="isVisible=!isVisible">{
{
isVisible }}</button>
<comChild v-if="isVisible" :n="n"></comChild>
</div>
</template>
<script>
// 导入的是对象,不是一个组件
// 导入、注册、使用
import comChild from "./components/comChild.vue";
console.log(comChild);
export default {
name: "App",
// 子组件comChild
components: {
comChild
},
data() {
return {
n:0,
isVisible: true
};
},
// 1、创建阶段(使用较少,异步加载)
beforeCreate() {
//创建前(初始化组件,准备组件自身的内容)
console.log("beforeCreate");
console.log(this.$data);//在组件创建之前,是没有数据的,那么这里直接输出this.$data,就是undefined
},
created() {
//创建后
console.log("created");
console.log(this.$data);
//数据(组件自身的)已经准备好了,即使它还没挂载。 {__ob__: Observer}
},
// 2、挂载阶段(组件和dom树,建立联系)
beforeMount() {
// 挂载前
console.log("beforeMount");
},
mounted() {
// 模板解析,及挂载
console.log("mounted");
console.log("el", this.$el