Dynamic components

Syntax for dynamic components

Dynamic components in Vue allow you to specify a single HTML placeholder for different components, after which the user/application can dynamically choose which component to display. The syntax of dynamic components is very similar to the syntax of the “slot” mechanism, except that in this case it is the so-called placeholder HTML element <component></component>. The selection of the desired component is done by defining the value of the special attribute v-bind:is="naziv-komponente"

Example

In this example there are 3 different components that need to be “printed” in the same place depending on the user’s wishes. The HTML tag <component></component> was used, which returns the corresponding component depending on the user’s action.

Life cycle of a dynamic component

dynamic components

The lifetime of a dynamic component begins with a dynamic switch to the component and ends with the loading of another component at the same place.

Example

In this example, methods are defined in the red component that print messages depending on whether the component is destroyed or newly created. Additional proof of component reloading when switching from one component to another, we get when every time after returning to the red component we notice that the counter is reset.

Keep alive dynamic components

If we want to change the default behavior of dynamic components and prevent the destruction and re-creation of the component instance after each switch, we need to wrap the component tag with the specific HTML element <keep-alive>.

When we wrap our dynamic component with a “keep-alive” element, the component is no longer destroyed, so the life-cycle hook (eng. hook) unmounted() (Vue 2: destroyed()) is no longer available to us. However, after using the <keep-alive> element, two other life-cycle hooks become available: activated() and deactivated()

Example

In this example it can be noticed that the counter value is not reset after changing the component. Also, every time a component is changed, the component is activated” and “deactivated”, which can be seen in the console.