Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
vuejs

How to use mixins in Vue.js

Shubham Singh Kshatriya

Overview

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.

Using a 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.

Syntax

// importing a mixin
import mixinName from '...'

export default {
  // registering a mixin
  mixins: [mixinName],
  ...
}

Example

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.

Code

// creating a method capitalize
export default {
    methods: {
        capitalize: function(str) {
            return str[0].toUpperCase() + str.slice(1);
        }
    }
}

Explanation

In the file capitalizeMixin.j we see the following:

  • Lines 4–6: We create a method 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:

  • Line 3: We create a h3 element to display str.
  • Line 4: We create another h3 element to display str, but this time we use the capitalize() method.

Inside the <script></script> tags, we see the following:

  • Line 9: We import the capitalizeMixin file
  • Line 12: We register the capitalizeMixin in this component.
  • Line 15: We create a variable str inside the data() function.

Output

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.

RELATED TAGS

javascript
vuejs

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring