Vue.jsWeb前端之路

vue父子组件 渲染过程,超详细

2019-08-20  本文已影响4人  一只大橘
这里vue的子组件引入有两中方式:同步和异步,因此父子组件加载的顺序
是不一样的,接着往下看,会有收获的。
一、 同步引入

例子: import Page from '@/components/page'

二、异步引入

例子:const Page = () => import('@/components/page')
或者: const Page = resolve => require(['@/components/page'], page)

image.png
同步引入时生命周期顺序为:父组件的beforeCreate、created、beforeMount --> 所有子组件的beforeCreate、created、beforeMount --> 所有子组件的mounted --> 父组件的mounted

例子:

  <! -- App.vue -->
<template>
  <div id="app">
    <New />  <!-- 子组件一 -->
    <Page /> <!-- 子组件二 -->
    <router-view/>
  </div>
</template>
<script>
import Page from '@/components/page' // 同步方式引入
import New from '@/components/new'
export default {
  name: 'App',
  components: {
    Page,
    New
  },
  beforeCreate () {
    console.log('父组件App -------> App beforeCreate')
  },
  created () {
    console.log('父组件App -------> App created')
  },
  mounted () {
    console.log('父组件App -------> App mounted')
  },
  beforeMount () {
    console.log('父组件App -------> App beforeMount')
  }
}
</script>
</script>

<!-- new.vue -->
<template>
    <div>
        <p>this is a new component</p>
    </div>
</template>

<script>
export default {
    name: 'new',
  created () {
    console.log('子组件new ----> new created')
  },
  beforeCreate () {
    console.log('子组件new ----> new beforeCreate')
  },
  mounted () {
    console.log('子组件new ----> new mounted')
  },
  beforeMount () {
    console.log('子组件new ----> new beforeMount')
  }
}
</script>
<!-- page.vue-->
<template>
    <div>
        <Job />
        <p>this is a page component</p>
    </div>
</template>

<script>
import Job from '@/components/job'
export default {
    name: 'page',
    components: {
        Job,
    },
    beforeCreate () {
        console.log('子组件page ----> page beforeCreate')
    },
    created () {
        console.log('子组件page ----> page created')
    },
    mounted () {
        console.log('子组件page ----> page mounted')
    },
    beforeMount () {
        console.log('子组件page ----> page beforeMount')
    }
}
</script>
<!-- job.vue -->
<template>
    <div>
        <p>this is a job component, in page.vue</p>
    </div>
</template>

<script>
export default {
    name: 'job',
  created () {
    console.log('孙组件job ------> job created')
  },
  beforeCreate () {
    console.log('孙组件job ------> job beforeCreate')
  },
  mounted () {
    console.log('孙组件job ------> job mounted')
  },
  beforeMount () {
    console.log('孙组件job ------> job beforeMount')
  }
}
</script>
image.png
异步引入时生命周期顺序:父组件的beforeCreate、created、beforeMount、mounted --> 子组件的beforeCreate、created、beforeMount、mounted

在上面的代码只需要修改引入的方式:

import Page from '@/components/page' // 同步方式引入
import New from '@/components/new'
import Job from '@/components/job'

改为:

const Page = () => import ('@/components/page')  // 异步引入
const New = () => import ('@components/new')
const Job = () => import ('@/components/job'
image.png

最后:为了加深映像,自己最好把例子跑一遍,喜欢就帮在下点点赞!!

上一篇下一篇

猜你喜欢

热点阅读