This page looks best with JavaScript enabled

Extend a component to create cool stuff

 ·   ·  ☕ 2 min read

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 -

1
2
3
4
5
<!-- 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 -

1
2
3
4
5
<!-- 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-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!-- 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>
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things