DEV Community

Cover image for Working with Dynamic Components in Vue.js
Deepak Sisodiya
Deepak Sisodiya

Posted on

Working with Dynamic Components in Vue.js

To understand what is a dynamic component, let's consider an example. Suppose we are developing a commenting platform where user can come and post a comment on the article. Posting of comment for the logged-in and logged-out user is different.

Alt text of image

Logged-in user

Alt text of image

Logged-out user

In the case of the logged-in user, we want to load CommentBoxLoggedIn component and for the logged-out user, we want to load CommentBoxLoggedOut component. Here we are mounting the component dynamically depending on if the user is logged-in or logged-out, that's where we want to use the dynamic component concept.

<Component 
  :is="dynamicComponent" 
  v-bind="dynamicComponentProps" 
/>

is attribute is a reference to the dynamic component and the v-bind attribute is used to pass dynamic component props. Let's see the example.

Alt text of image

Using a dynamic component

In the example above we are calculating the dynamic component and dynamic component props as a computed prop. Notice the parentId is always 0 in case of the top-level comment.

This looks like a simple if/else solution. But using this approach we can make our code more scalable and readable moving the logic out of the template. We can also add animation with a dynamic component using Vue.js Transition https://vuejs.org/v2/guide/transitions.html#Transitioning-Between-Components

This approach has one more advantage. Suppose we have reply action in each comment of the article. On click of reply action, we want to load the same dynamic component CommentBoxLoggedIn and CommentBoxLoggedOut depending on if the user logged-in or logged-out but with modified/different props.

For this, we can pass the computed props commentBoxComponentName and commentBoxComponentProps to a child component, let say to CommentItem component which renders single comment. Now CommentItem component receiving the commentBoxComponentProperties and commentBoxComponentName as a props. Let's see the example

Alt text of image

Extending the dynamic component props and using in the template

In the example above we are extending commentBoxComponentProperties with parentId because in case of reply parentId is different for each comment. and at the same time, we are using dynamic components in the template. This way we are making our code more structured and manageable.

Top comments (0)