How to dynamically load components in Vue.js?

Vue.js allows you to dynamically load components using v-bind:is or the :is directive. This is useful for conditional rendering of components.

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

<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';

export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    };
  },
  methods: {
    toggleComponent() {
      this.currentComponent = (this.currentComponent === 'ComponentA') ? 'ComponentB' : 'ComponentA';
    }
  }
};
</script>

In this example, clicking a button could toggle between loading ComponentA and ComponentB.

Post your Answer