In Vue.js, mixins are used to share reusable functionalities among the components and can contain any of the component's options. All the options in the mixin get mixed into the component’s own options when it uses that mixin.
To use a mixin in a component, we need to import and register the mixin.
To import a mixin, we use the import
statement, and to register a mixin, we have to add the imported mixin name in the mixins option of the component. An example of it is as follows.
// importing a mixin
import mixinName from '...'
export default {
// registering a mixin
mixins: [mixinName],
...
}
In this example, we'll create a mixin and then import and register that mixin in a Vue component.
Let's jump to the code.
// creating a method capitalize export default { methods: { capitalize: function(str) { return str[0].toUpperCase() + str.slice(1); } } }
In the file capitalizeMixin.j
we see the following:
capitalize()
that accepts a string as an argument, capitalizes it, and returns it.Note: We'll use the
capitalizeMixin.js
file as a mixin in our Vue component.
In the file Example.vue
, we see the following two instances.
Inside the <template></template>
tags, we see the following:
h3
element to display str
.h3
element to display str
, but this time we use the capitalize()
method.Inside the <script></script>
tags, we see the following:
capitalizeMixin
filecapitalizeMixin
in this component.str
inside the data()
function.After registering the capitalizeMixin
in the Example.vue
component, all of the options declared in capitalizeMixin.js
are also a part of Example.vue
options.
Therefore, even though we don't have any methods in Example.vue
, we can invoke the capitalize()
method in line 4, and see the capitalized string.