Vue Dynamic Components
Using the ‘is’ attribute, Dynamic Components can be used to navigate between pages on your page, much like tabs in a browser.
The Component Tag and The 'is' Attribute
The <component> element is used to indicate the active component when creating a dynamic component. We use v-bind to attach the ‘is’ property to a value, which we then set to the name of the component we want to be active.
Example
The element in this example serves as a stand-in for either the comp-one or the comp-two <component>. Set on the <component> tag, the ‘is’ attribute watches for the calculated value ‘activeComp’, which may include ‘comp-one’ or ‘comp-two’. Additionally, to enable the computed value to alternate between the active components, we have a button that toggles a data attribute between “true” and “false.”
App.vue:
Dynamic Components
App.vue switches between which component to show.
< KeepAlive >
Try the following example. When you move back to a component, you’ll find that whatever modifications you make are lost. This is a result of the component being reloaded by being unmounted and then mounted again.
Example
The user inputs are now remembered by the components.
App.vue:
Dynamic Components
App.vue switches between which component to show.
The 'include' and 'exclude' Attributes
By default, any elements enclosed in the <KeepAlive> tag will remain active.
However, by utilizing the ‘include’ or ‘exclude’ attributes on the <KeepAlive> tag, we may also specify which components should be kept alive solely.
In the event that the <KeepAlive> tag is used with the ‘include’ or ‘exclude’ attributes, the components must additionally be given names using the ‘name’ option:
CompOne.vue:
Example
Only the ‘CompOne’ component will remember its state and the previous inputs when <KeepAlive include=”CompOne”> is used.
App.vue:
Dynamic Components
App.vue switches between which component to show.
‘Exclude’ is another tool we can use to decide which components to leave alive or not.
Example
Only the ‘CompTwo’ component will remember its state when <KeepAlive exclude=”CompOne”> is used.
App.vue:
Dynamic Components
App.vue switches between which component to show.
By employing comma separation, “include” and “exclude” can both be used with numerous components.
We will add one more component to demonstrate this, for a total of three components.
Example
The ‘CompOne’ and ‘CompThree’ components will both remember their states when <KeepAlive include=”CompOne, CompThree”> is used.
App.vue:
Dynamic Components
The 'max' Attribute
To reduce the amount of components the browser must remember the state of, we can use the’max’ attribute to the <KeepAlive> element.
Example
The browser will only retain the user input of the previous two components it visits when <KeepAlive:max=”2″> is used.
App.vue:
Dynamic Components