vue同步父子组件和异步父子组件的生命周期顺序问题
程序员文章站
2023-11-11 23:06:52
关于vue组件的引入方式有两种
一、 同步引入
例子: import page from '@/components/page'
二、异步引入
例子:const p...
关于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'
结果:
总结
以上所述是小编给大家介绍的vue同步父子组件和异步父子组件的生命周期顺序问题,希望对大家有所帮助
上一篇: 网店推广软文写作技巧