Mixins
Learn about Vue's mixins, a go-to method for creating reusable code, and how they relate to inheritance.
We'll cover the following...
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:
export default {data() {return {someData: 'someString'}}}
We can also add mixins to a component, as shown below:
<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 ...