简体   繁体   中英

How is Vue.js component Created() order set?

Given two components, both loaded into a third component, what determines the order that the created lifecycle for each will fire?

Top Level Component

<template>
   <div>
        <start-date-filter />
        <end-date-filter />
   </div>
</template>

<script>
import StartDateFilter from './StartDateFilter.vue';
import EndDateFilter from './EndDateFilter.vue';

export default {
    components: {
       StartDateFilter,
       EndDateFilter
    }
}
</script>

StartDateFilter Component

<script>
export default {
   created() {
      console.log('made it first');
   }
}
</script>

EndDateFilter Component

<script>
export default {
   created() {
      console.log('made it second');
   }
}
</script>

I don't believe the ordering is guaranteed. It isn't something you should really be relying on, ideally sibling components shouldn't be talking to each other directly so it shouldn't matter.

In general when Vue renders it will try to reuse child components from the previous render. Various factors influence the VNode matching algorithm to determine which old nodes are paired up to which new nodes. Any components for nodes that already exist won't have their created hook called at all.

Considering just the simple case of a fresh render with no existing components...

You can see how the current code handles this by using debugger statements instead of just console logging. When paused in the debugger you can look through the call stack to see how the components get created.

Currently it appears that Vue will process the children in the order they appear in the children array of the VNode. The method createChild just loops through the array of children that it's passed and that array comes from createElm , which gets it from vnode.children .

I believe that should mean that the created hooks for components will be called in the order they appear in the template, so long as there aren't any slots involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM