Vue’s Dynamic Components

Posted by


Dynamic components in Vue are a powerful feature that allows you to dynamically switch between different components within your Vue application. This can be useful when you have different components that you want to display based on certain conditions or user interactions.

In this tutorial, we will go over how to use dynamic components in Vue and provide examples to help you understand how they work.

Setting Up the Project

To get started with dynamic components in Vue, you will need to have Vue installed in your project. You can do this by using Vue CLI to create a new project or by adding Vue to an existing project.

Here’s the command to install Vue CLI if you don’t already have it:

npm install -g @vue/cli

Next, create a new Vue project using the following command:

vue create dynamic-components-example

After the project has been created, navigate to the project directory and install the Vue Router package, which we will use for handling dynamic components:

npm install vue-router

Creating Dynamic Components

In order to use dynamic components in Vue, we need to define the components that we want to switch between. Let’s create two simple components for demonstration purposes.

First, create a component named HomeComponent.vue:

<template>
  <div>
    <h1>Welcome to the Home Page</h1>
  </div>
</template>

Next, create a component named AboutComponent.vue:

<template>
  <div>
    <h1>About Us</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  </div>
</template>

Now that we have our components set up, let’s create a parent component named DynamicComponent.vue that will dynamically switch between the Home and About components based on a user interaction.

<template>
  <div>
    <button @click="showHome">Show Home</button>
    <button @click="showAbout">Show About</button>

    <component :is="currentComponent"></component>
  </div>
</template>

<script>
import HomeComponent from './HomeComponent.vue'
import AboutComponent from './AboutComponent.vue'

export default {
  data() {
    return {
      currentComponent: 'HomeComponent'
    }
  },
  components: {
    HomeComponent,
    AboutComponent
  },
  methods: {
    showHome() {
      this.currentComponent = 'HomeComponent'
    },
    showAbout() {
      this.currentComponent = 'AboutComponent'
    }
  }
}
</script>

In the above code, we are dynamically switching between the HomeComponent and AboutComponent by updating the currentComponent data property based on the user’s clicks on the buttons.

Registering Components

In order for the components to be recognized by Vue, we need to register them with Vue. This can be done in the main.js file where we create the Vue instance.

import Vue from 'vue';
import DynamicComponent from './DynamicComponent.vue';

new Vue({
  render: h => h(DynamicComponent),
}).$mount('#app');

Now, run the Vue application using the following command:

npm run serve

Open your browser and navigate to http://localhost:8080 to see the dynamic components in action. You should see two buttons – "Show Home" and "Show About" – which will switch between the Home and About components when clicked.

Conclusion

Dynamic components in Vue are a powerful tool that allows you to dynamically switch between different components based on user interactions or conditions. In this tutorial, we created dynamic components in Vue by defining two components – HomeComponent and AboutComponent – and a parent component – DynamicComponent – to switch between them.

By following this tutorial, you should have a better understanding of how to use dynamic components in Vue and how they can be used to create more flexible and interactive Vue applications.

0 0 votes
Article Rating

Leave a Reply

26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@caiovinicius2718
2 hours ago

ammmmmmmmmmmmmmmazing

@korbinperry6906
2 hours ago

By chance could you elaborate just a little, you mentioned the "flash avoidance strategy" and I perked up a bit.

Our fairly large site has just migrated to Nuxt and we've experienced some flashing, I suspect mostly actually due to SSR / CSR issues and some changes we need to make, but perhaps this is more common than I know 😅

@beia-rl2dw
2 hours ago

Awesome video, it is very helpful for me!!!

@svenvanreenen
2 hours ago

Great video Alex! Mine was really using an old JS switch case to render components dynamically but will definitely see how this can improve the case.

@ubaydillah1535
2 hours ago

i fans antfu

@VladyslavOstapko
2 hours ago

Thanks!

@bluntman2k6
2 hours ago

Back in my days I had to register my global components in the nuxt.config.ts. Good to know that you can now add a .globals suffix. Or a folder. Nuxt gives you really everything 😅

@swissmexxa
2 hours ago

Problem in Nuxt, if you use a dynamic component and use useFetch (or useAsyncData) in the dynamic loaded component, the useFetch won‘t recognize the payload key in the DOM while hydrating and refetch the data on hydration. This is a big problem when working with storybloks own dynamic component. We had to create a wrapper around useFetch because of this.

@TarasShabatin
2 hours ago

I guess the better name would be isAnotherDynamicComponentShown or isAnotherDynCompShown instead of isSwitched.

Your variables' names must represent what it is storing.

Your methods' names must represent what those methods are doing.

Long live to Uncle Bob and "Clean Code".

@valacshiro378
2 hours ago

Amazing and helpful as always, love this videos keep it going 😀

Thank you very much for the time a effort to make this. I always leran something new 😊

@shakur_t
2 hours ago

This was a very great and useful video, thank u for sharing it

@tolgabeyazoglu536
2 hours ago

Like your previous video on how to use the lazy component, this is a very useful video thank you

@lbmgary
2 hours ago

Love this video. For our CMS we allow the editor to select the components that will be present on any given page. To handle that we use vite to inject at build time all of these special components that our customer has access to use. Pretty simple. I really wish we could use a variable in resolve but it's probably due to knowing what component is needed at build time. idk, maybe there is another more elegant way b/c with enough components it gets a little messy on the output with all those Lazy components waiting to pop off.

@Aguycalledmax
2 hours ago

How would you handle dynamic components if they accepted different props?
Is there a way to pass props within resolvecomponent or would you use something like a computed v-bind?

@KuroManX
2 hours ago

Vue dynamic components + Strapi dynamic zones, best combo for a CMS.

@РодионГаврилов-ч9ж
2 hours ago

haha)) its broken O.O

@EvestDev
2 hours ago

Well, i have some code to update XD. Thx a bunch for the video ❤️

@adiprimanto8871
2 hours ago

anybody know how to make webpage builder? is there any library recommendations ?

@Wojtasvx
2 hours ago

Very good tutorial, I am waiting for more!

@Gornius
2 hours ago

Had no idea that Lazy components existed, but they are so useful!

26
0
Would love your thoughts, please comment.x
()
x