Composing Vue.js Components

Joshua Bemenderfer

An oft-overlooked feature of Vue.js is component composition. It allows you to extend and inherit one or more components with minimal effort in order to provide reusable functionality across your app.

Extension works by merging another component’s options with your component. Duplicate properties will be overwritten by your component, and duplicate methods will be called one after another.

Extends

Extends allow you to extend a single other component, with your component’s options taking higher priority over the parent component’s. This means, for example, that if both the parent and your component contain a created() hook, your component’s created() hook will be called first, then the parent’s.

ParentComponent.vue

<script>
export default {
  created() {
    console.log('Created from the parent!');
  }
}
</script>

ChildComponent.vue

<script>
import ParentComponent from './ParentComponent.vue';

export default {
  extends: ParentComponent,

  created() {
    console.log('Created from the child!');
  }
}
</script>

Output:

Created from the child!
Created from the parent!

Mixins

Mixins are even cooler. They allow you to extend multiple component definitions. Using mixins, it’s simple to provide reusable methods and data across any number of your components.

The only major difference being that mixin hooks are called in order, before your component’s own hooks.

my-mixins.js

export const mixin1 = {
  created() {
    console.log('Created Mixin 1');
  }
}

export const mixin2 = {
  created() {
    console.log('Created Mixin 2');
  }
}

export const mixin3 = {
  mounted() {
    console.log('Mounted Mixin 3');
  }
}

export const mixin4 = {
  mounted() {
    console.log('Mounted Mixin 4');
  }
}

ChildComponent.vue

<script>
import {mixin1, mixin2, mixin3, mixin4} from './my-mixins.js';

export default {
  mixins: [mixin1, mixin2, mixin3, mixin4],

  created() {
    console.log('Created from the child!');
  },

  mounted() {
    console.log('Mounted from the child!');
  }
}
</script>

Output:

Created Mixin 1
Created Mixin 2
Created from the child!

Mounted Mixin 3
Mounted Mixin 4
Mounted from the child!

Global Mixins

Mixins can also be registered globally, injecting their functionality into every single Vue component. This might be useful for logging or debugging, but is generally not used outside of plugins. Be warned, global mixins will modify the functionality of every single component in your app, even third-party ones, so it’s generally not a good idea to use them unless you have a clear idea what you’re doing.

To create a global mixin, register it with Vue.mixin.

import Vue from 'vue';

Vue.mixin({
  created() {
    // Will be called every time a component is created.
    console.log('Mixin created!');
  }
})

Search

🔎 Searching...