How do I extend another VueJS component in a single-file component? (ES6 vue-loader)

Viewed 51182

I am using vue-loader to construct my *.vue single-file components, but I am having trouble with the process of extending a single-file component from another.

If one component follows the spec to export default { [component "Foo" definition] }, I would think it is just a matter of importing this component (as I would with any child component) and then export default Foo.extend({ [extended component definition] })

Unfortunately this does not work. Can anyone please offer advice?

5 Answers

I'd avoid the "extends" feature of Vue, simply because it is a poorly named method of Vue. It doesn't really extend anything, not in the case of inheritance. What it does is exactly what the mixin does, it merges the two components together. It has nothing to do with the template code, which isn't extensible either. The "extend" Vue method should have been called "merge".

At any rate, Vue must work with the hierarchy of the DOM and thus it composes to the DOM. That same thinking should rule your SFC building. Use component mixins for base behavior and add the mixins to your components as you need that behavior, while composing together the smallest common parts into bigger parts, all at the same time keeping your template code to a minimum. You should think "thin views, think models" while composing your SFCs. :)

As of Vue 3, the Composition API is introduced, making it very easy to share state across components.

Rather than defining your component with properties on the component definition object e.g. data, computed, methods, etc, the Composition API allows you to instead create a setup function where you declare and return these.

An example:

file: useCounter.js

import { reactive, computed } from "vue";

export default function {
  const state = reactive({
    count: 0,
    double: computed(() => state.count * 2)
  });

  function increment() {
    state.count++
  }

  return {
    count,
    double,
    increment
  }
}

Now the counter feature can be seamlessly introduced into any Vue component using it's setup function:

file: MyComponent.vue

<template>
   <button @click="increment">
      Count is: {{ count }}, double is: {{ double }}
   </button>
</template>

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

export default {
  setup() {
    const { count, double, increment } = useCounter();
    return {
      count,
      double,
      increment
    }
  }
}
</script>

One of the main benefits of declaring a component using the Composition API is that it makes logic reuse and extraction very easy. Composition functions are the most straightforward and cost-free way of extending a component by making its features modular and reusable.

Related