0 votes
in VueJS by
What are dynamic components in VueJS?

1 Answer

0 votes
by

The dynamic component will allow you to dynamically switch beetween multiple components without updating the route of the application and even retaining the state of the component when switching back to the initial component. It works by using <component> tag with v-bind:is attribute which accept dynamic component.

Let's create a dynamic component vue instance to switch between different pages of a website,

new Vue({
  el: '#app',
  data: {
    currentPage: 'home'
  },
  components: {
    home: {
      template: "<p>Home</p>"
    },
    about: {
      template: "<p>About</p>"
    },
    contact: {
      template: "<p>Contact</p>"
    }
  }
})

Now you can use the dynamic component which holds the current page,

<div id="app">
   <component v-bind:is="currentPage">
       <!-- component changes when currentPage changes! -->
       <!-- output: Home -->
   </component>
</div>

The component will be unmounted when it is switched away but it is possible to force the inactive component alive using <keep-alive> component

Related questions

0 votes
asked Sep 9, 2023 in VueJS by DavidAnderson
0 votes
asked Sep 6, 2023 in VueJS by DavidAnderson
...