Skip to content
Advertisement

Use of common methods within other Vue components

What is the proper way to use method isValidEmail within compA.vue and some other hypothetical compB.vue?

This approach doesn’t work for me:

JavaScript

Advertisement

Answer

You can simply use mixins: you define in the mixin the function isValidEmail and then you import the mixin in the components you need.

https://v2.vuejs.org/v2/guide/mixins.html – Vue v2
https://v3.vuejs.org/guide/mixins.html – Vue v3

For example, instead creating a component Validators.vue as you did in your example, you can create a mixin named Validators.js as per below:

JavaScript

Then you can import the mixin in the components you need:

JavaScript

In this way, the component CompA will inherit all the functions, data and computed property defined in the mixin.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement