vue 组件初始化为啥不执行activated分析

前提:组件通过keep-alive标签缓存

问题描述:页面初始化时即页面第一次打开或者刷新浏览器时,父组件会执行created和activated

子组件只执行created 不执行activated

结论:子组件在页面初始化时没有加载,而是通过异步请求方式来控制组件是否要加载 通过v-if来控制的,这样导致页面父组件已经初始化完成时子组件才开始渲染,从而不执行子组件的activated钩子函数

后延时函数换成new Promise函数后可以实现子组件初始化时执行activated,所以我弱弱的觉得是父组件执行activated之前渲染子组件,就可以初始化时触发子组件的activated

<template>
  <div id="app">
   <keep-alive>
     <router-view/>
   </keep-alive>    
  </div>
</template>
//父组件
<template>
  <div class="about">
    父组件   
    <child-cpn v-if='show'></child-cpn>
  </div>
</template>
<script>
import ChildCpn from './ChildCpn'
export default{
  name:'AboutView',
  components:{
    ChildCpn
  },
  data(){
    return{
      show:false
    }
  },
  created(){
   console.log('父组件created被执行')
   setTimeout(()=>{
    this.show=true//模拟异步获取后处理逻辑,此处控制子组件是否渲染
   },1000)   
  },
  activated(){ 
    console.log('父组件的activated')//经验证初始化时都会执行activated    
  }
}
//子组件
<template>
    <div class="about">
      我是子组件
    </div>
</template>
<script>
export default{
    name:'AboutView',

    created(){
      this.show=true   
      console.log('子组件的created')//初始化时都会执行
   },
   activated(){    
    //初始化时不会执行这行,但是从别的页面过来时 总之组件已经缓存后才会执行     
     console.log('子组件的activated')
  },
}
</script>

猜你喜欢

转载自blog.csdn.net/uniquepeng/article/details/130146047