Extend a component to create cool stuff

Vue enables you to extend a component, thereby carrying forward all the base elements and add some more. This is one of the efficient ways for component composition.

Let’s say you have a simple panel that you use everywhere -

<!-- MainPanel.vue -->
<template>
  <!-- main area -->
  <!-- panel footer -->
</template>

Now, you get this super idea to include a title in the panel. Normally you would just have a tag that conditionally renders based on prop and thereby control whether title shows up or not.

But, hey - you can also do it in another component altogether. No one has the right to judge.

You create a new component thusly -

<!-- MainPanelWithTitle.vue -->
<template>
  <!-- main area -->
  <!-- panel footer -->
</template>

Now, what happens when you have to add a notification in the panel? Change both components - pfft.. we live in 2030 and don’t do all that.

So, extends. Extends allow you to inherit everything from a component and add more stuff to it.

Let us rewrite the earlier component using extends-

<!-- MainPanelWithTitle.vue -->
<template>
  <p class="title">{{ title }}</p>
  <!-- main area -->
  <!-- panel footer -->
</template>

<script>
  import MainPanel from "./MainPanel";

  export default {
    extends: MainPanel,
    props: ["title"]
  };
</script>
comments powered by Disqus