1. 程式人生 > >vue--同步父子元件和非同步父子元件的生命週期順序

vue--同步父子元件和非同步父子元件的生命週期順序

關於vue元件的引入方式有兩種

一、 同步引入

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

二、非同步引入

例子:const Page = () => import('@/components/page')
或者: const Page = resolve => require(['@/components/page'], page)
兩種引入方式的不同之處在於:

同步引入時生命週期順序為:父元件的beforeMount、created、beforeMount --> 所有子元件的beforeMount、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>

在這裡插入圖片描述

非同步引入時生命週期順序:父元件的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'

結果: 在這裡插入圖片描述