Go Back Buy Me A Coffee 😇

VueJS Dynamic Component and Why it is Useful

/ Let us look at how we can dynamically use components using the VueJS "<component />" tag and look at the importance. Let us improve our code and optimize it by simplifying our code.

#vue
#vuejs
#vue-tip
#VueJs
#Programming
✍️ BroJenuel
May. 11, 2023. 5:47 AM

If you have not heard of VueJS before

Vue.js (pronounced /vjuː/, like view) is a progressive JavaScript framework for building user interfaces. It is designed to be flexible and incrementally adoptable and can be used to build a wide range of web applications, from simple websites to complex single-page applications (SPAs).

Vue.js has a number of key features that make it a popular choice for front-end development:

  • Declarative rendering: Vue.js uses a declarative template syntax that makes it easy to describe the user interface of your application.

  • Reactivity: Vue.js automatically tracks changes to your application's data and updates the DOM accordingly. This makes it easy to build dynamic and interactive user interfaces.

  • Component-based: Vue.js uses a component-based approach to development. This makes it easy to reuse code and create complex user interfaces from smaller, more manageable pieces.

Vue.js also has a number of other features that make it a powerful and versatile framework, including:

  • Two-way data binding: Vue.js makes it easy to bind data to HTML elements, so that changes to the data are automatically reflected in the UI, and vice versa.

  • Directives: Vue.js provides a number of directives that can be used to add additional functionality to HTML elements.

  • Filters: Vue.js provides a number of filters that can be used to format data before it is displayed in the UI.

  • Transition effects: Vue.js provides a number of built-in transition effects that can be used to animate changes to the UI.

Vue.js is a popular choice for front-end development because it is easy to learn, yet powerful enough to build complex and scalable web applications. It is also backed by a large and active community, which means that there is a wealth of resources available to help you learn and use Vue.js.

Here are some of the most popular websites and applications built with Vue.js:

  • GitLab

  • Upwork

  • Laravel Nova

  • DevTools for VS Code

  • Xiaomi

  • Behance

  • Grammarly

  • Bilibili

  • Douyu

  • Netlify

If you are interested in learning more about Vue.js, there are a number of resources available online, including the official Vue.js documentation and tutorials. There is also a large and active community of Vue.js developers who are always willing to help new users. https://vuejs.org/

VueJS Dynamic Component

Sometimes, it's useful to dynamically switch between components, like in a tabbed interface. The above is made possible by Vue's <component> element with the special is attribute. In this article I will show a sample why dynamic form is very useful.

You can copy the source code HERE. Assuming we want to render the component based on a key, As you can see in the code below we created a page that displays the component based on the selected page.

<script lang="ts" setup>
import { ref } from "vue";
import PageOne from "./components/PageOne.vue";
import PageTwo from "./components/PageTwo.vue";
import PageThree from "./components/PageThree.vue";

const selectedPage = ref("one");
</script>

<template>
    <h1>This Are Pages</h1>

    <button @click="selectedPage = 'one'">Select Page One</button>
    <button @click="selectedPage = 'two'">Select Page Two</button>
    <button @click="selectedPage = 'three'">Select Page Three</button>

    <PageOne v-if="selectedPage == 'one'" />
    <PageTwo v-if="selectedPage == 'two'" />
    <PageThree v-if="selectedPage == 'three'" />
</template>

In the code above, we added the 3 components and based on the condition, it only shows the component based on the selected value from "one", "two", and "three". This is good but can become a problem if we have too many components to render, and it would be a hassle if we will add more components later on, right? It would be awesome if can create a way to automate this when ever we add a new component, right?

So the first thing to do is to put them in a variable or you can put it in:

import PageOne from "./components/PageOne.vue";
import PageTwo from "./components/PageTwo.vue";
import PageThree from "./components/PageThree.vue";

const pagesToRender = [
    {
        title: "Page One",
        key: "one",
        component: PageOne,
    },
    {
        title: "Page Two",
        key: "two",
        component: PageTwo,
    },
    {
        title: "Page Three",
        key: "three",
        component: PageThree,
    },
];

And Then we can turn our template to look something like this:

<template>
    <h1>This Are Pages</h1>

    <button v-for="page in pagesToRender" :key="'btn-' + page.key" @click="selectedPage = page.key">{{ page.title }}</button>

    <component :is="pagesToRender.find((item) => item.key == selectedPage)?.component as any" />
</template>

Now, our buttons are dynamic and automatically renders button with a label of title, and if we click the button it will set the selectedPage value based on the object key which is "one", "two", and "three".

We then used the `component` tag, and we used the `is` property for us to render the component dynamically based on the selected key, and then returns the component property which includes the component we imported.

So with that said our code should look like this:

<script lang="ts" setup>
import { ref } from "vue";
import PageOne from "./components/PageOne.vue";
import PageTwo from "./components/PageTwo.vue";
import PageThree from "./components/PageThree.vue";

const selectedPage = ref("one");
const pagesToRender = [
    {
        title: "Page One",
        key: "one",
        component: PageOne,
    },
    {
        title: "Page Two",
        key: "two",
        component: PageTwo,
    },
    {
        title: "Page Three",
        key: "three",
        component: PageThree,
    },
];
</script>

<template>
    <h1>This Are Pages</h1>

    <button v-for="page in pagesToRender" :key="'btn-' + page.key" @click="selectedPage = page.key">{{ page.title }}</button>

    <component :is="pagesToRender.find((item) => item.key == selectedPage)?.component as any" />
</template>

We can also create an external TypeScript/JavaScript, a place for us to dynamically edit the menu menu. So in this example I created a file in `src/utility/PagesToRender.ts` that contain this code:

import PageOneVue from "@/components/PageOne.vue";
import PageThreeVue from "@/components/PageThree.vue";
import PageTwoVue from "@/components/PageTwo.vue";

const pagesToRender = [
    {
        title: "Page One",
        key: "one",
        component: PageOneVue,
    },
    {
        title: "Page Two",
        key: "two",
        component: PageTwoVue,
    },
    {
        title: "Page Three",
        key: "three",
        component: PageThreeVue,
    },
];

export default pagesToRender;

Then we can just import it to our main template like this:

<script lang="ts" setup>
import { ref } from "vue";
import pagesToRender from "./utility/PagesToRender";

const selectedPage = ref("one");
</script>

<template>
    <h1>This Are Pages</h1>

    <button v-for="page in pagesToRender" :key="'btn-' + page.key" @click="selectedPage = page.key">{{ page.title }}</button>

    <component :is="pagesToRender.find((item) => item.key == selectedPage)?.component as any" />
</template>

Imported the pagesToRender from our utility. Now whenever we add a page we can just go to our pageToRender utility and add more pages.

Why Use Dynamic Components

There are a number of reasons to use dynamic components in Vue.js:

  • To create more flexible and interactive user interfaces: Dynamic components allow you to swap out components at runtime based on the current state of your application or user interactions. This can be useful for creating things like tabbed interfaces, wizards, and other complex user interfaces.

  • To improve performance: By only rendering the components that are currently needed, dynamic components can help to improve the performance of your application. This is especially important for large and complex applications.

  • To make your code more reusable and maintainable: Dynamic components can be used to create reusable components that can be used in different parts of your application. This can make your code more maintainable and easier to update.

Here are some specific examples of how dynamic components can be used in Vue.js:

  • Tabbed interface: You can use dynamic components to create a tabbed interface where the user can switch between different tabs by clicking on the tab headers.

  • Wizard: You can use dynamic components to create a wizard where the user progresses through a series of steps by clicking on buttons.

  • Product carousel: You can use dynamic components to create a product carousel where the user can browse through a list of products by swiping left or right.

  • Infinite scrolling: You can use dynamic components to create infinite scrolling where new items are loaded into the list as the user scrolls down.

  • Real-time chat: You can use dynamic components to create a real-time chat where messages are updated in real time as they are sent and received.

Overall, dynamic components are a powerful feature of Vue.js that can be used to create more flexible, interactive, and performant user interfaces.

Here are some additional benefits of using dynamic components in Vue.js:

  • Reduced code duplication: Dynamic components allow you to reuse the same component definition in different parts of your application. This can reduce code duplication and make your code more maintainable.

  • Improved readability: Dynamic components can make your code more readable by encapsulating complex logic into reusable components.

  • Enhanced testability: Dynamic components can make your code more testable by allowing you to isolate and test individual components.

If you are developing complex Vue.js applications, I recommend using dynamic components to make your code more flexible, reusable, maintainable, and testable.

We use component tags to dynamically render our component, this is useful because we don't have to write every component we created, instead using the component tag we can render our component using a single tag. I hope you learn something from this short article! aloha! mabuhay!


If you enjoy this article and would like to show your support, you can easily do so by buying me a coffee. Your contribution is greatly appreciated!

Buy Me a Coffee at https://www.buymeacoffee.com