只有用keep-alive包裹的组件,才会触发下面的生命周期
<template>
<div style="background-color: aliceblue">
<h1> this is ChildrenComp2 </h1>
<p>{{ num }}</p>
<button @click="num++">num ++ </button>
</div>
</template>
<script>
export default {
name: "ChildrenComp2",
data(){
return {
num:0
};
},
beforeCreate() {
console.log('一、创建实例之前自动调用 beforeCreate');
},
created() {
console.log('二、实例之创建完成自动调用 created');
},
beforeMount() {
console.log('三、模板编译之前自动调用 beforeMount');
},
mounted() {
console.log('四、模板编译完成自动调用 mounted');
},
beforeUpdate() {
console.log('五、模板更新之前自动调用 beforeUpdate');
},
updated() {
console.log('六、模板内容更新完成自动调用 updated');
},
// 缓存
activated() {
console.log('activated');
},
deactivated() {
console.log('deactivated');
},
// 销毁
beforeUnmount() {
console.log('七、实例在销毁之前调用 beforeUnmount');
},
unmounted() {
console.log('八、实例销毁完成调用 unmounted');
}
}
</script>
<style scoped>
</style>
<template>
<button @click="isShow=!isShow">显示/隐藏</button>
<ChildrenComp2 v-if="isShow">
</ChildrenComp2>
</template>
<script>
import ChildrenComp2 from "./components/ChildrenComp2";
export default {
name: 'App',
components:{
ChildrenComp2
},
data(){
return {
isShow:false
}
},
}
</script>
<!--scoped 限制局部样式-->
<style lang="scss">
</style>
beforeUpdate
和 updated
使用
上面演示当改变num之后,然后销毁组件,再显示的时候,组件会被重新创建,num也会被重新初始化。所以num=0了。
而当在根组件上使用keep-alive标签后,
this.$nextTick(()=>{
// this.$refs.username.focus();
})
暂时不是很明白,待补充
<template>
<button @click="isShow=!isShow">显示/隐藏button>
<keep-alive>
<ChildrenComp2 v-if="isShow">
ChildrenComp2>
keep-alive>
template>
<script>
import ChildrenComp2 from "./components/ChildrenComp2";
export default {
name: 'App',
components:{
ChildrenComp2
},
data(){
return {
isShow:false
}
},
}
script>
<style lang="scss">
style>
<template>
<div style="background-color: aliceblue">
<h1> this is ChildrenComp2 h1>
<p>{{ num }}p>
<button @click="num++">num ++ button>
div>
template>
<script>
export default {
name: "ChildrenComp2",
data(){
return {
num:0
};
},
beforeCreate() {
console.log('一、创建实例之前自动调用 beforeCreate');
},
created() {
console.log('二、实例之创建完成自动调用 created');
},
beforeMount() {
console.log('三、模板编译之前自动调用 beforeMount');
},
mounted() {
console.log('四、模板编译完成自动调用 mounted');
},
beforeUpdate() {
console.log('五、模板更新之前自动调用 beforeUpdate');
},
updated() {
console.log('六、模板内容更新完成自动调用 updated');
},
// 缓存
activated() {
console.log('activated');
},
deactivated() {
console.log('deactivated');
},
// 销毁
beforeUnmount() {
console.log('七、实例在销毁之前调用 beforeUnmount');
},
unmounted() {
console.log('八、实例销毁完成调用 unmounted');
}
}
script>
<style scoped>
style>