Search⌘ K
AI Features

Mixins

Explore how VueJS mixins help you abstract and reuse logic across multiple components. Understand lifecycle hook stacking, custom merge strategies, and using multiple mixins while maintaining manageable code complexity.

This lesson will look at the go-to method for creating reusable code, mixins. Mixins are an excellent way to abstract away similar logic from otherwise different components. Use cases could be form validation, loading user data, or throwing custom events.

What is a mixin?

Mixins are code that we can plug into any component. They’re comparable to the modern-day PHP’s trait feature, which offers the same service. A mixin itself is a component. It provides lifecycle hooks, methods, data, computed fields, and all the things any other component offers. Let’s define a simple mixin as a renderless component:

Javascript (babel-node)
export default {
data() {
return {
someData: 'someString'
}
}
}

We can also add mixins to a component, as shown below:

HTML
<template>
<div>
{{ someData }}
</div>
</template>
<script>
import MyMixin from '../mixins/MyMixin'
export default {
mixins: [ MyMixin ],
}
</script>

By convention, mixins don’t live in the “src/components” folder but in a separate folder called “src/mixins”. This way, we can always identify ...