组件复用,生命周期问题

路由组件在复用的时候切换路由时,因为组件的复用,导致不会走完整的生命周期,有些在 mounted 和 created 生命周期函数中的方法就不会执行,由此产生疑问,在组件中引入的子组件,在路由父组件切换的时候,子组件会不会走mounted 和 created

父组件1:

<template>
  <div>
    <span>我是父组件111</span>
    <Child></Child>
  </div>
</template>

<script>
import Child from './Child'
export default {
  components: { Child }
}
</script>

父组件2:

<template>
  <div>
    <span>我是父组件222</span>
    <Child></Child>
  </div>
</template>

<script>
import Child from './Child'
export default {
  components: { Child }
}
</script>

子组件:

<template>
  <div>
    <span>我是子组件</span>
  </div>
</template>

<script>
export default {
  mounted () {
    console.log('子组件的mounted方法执行了')
  },
  created () {
    console.log('子组件的created方法执行了')
  }
}
</script>

路由:

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/parent1',
        component: Parent1
      },
      {
        path: '/parent2',
        component: Parent2
      }
    ]
  }
]

结果:
image

结论:父组件切换,子组件复用,子组件的 created 和 mounted 也会执行,可以做初始化工作,路由组件复用则不会。

posted @ 2021-06-02 17:29  脉望  阅读(182)  评论(0编辑  收藏  举报