Use of common methods within other Vue components

Tags: ,



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:

<template>
    <div></div>
</template>
<script>
export default {
    name: 'Validators',
    methods: {
        isValidEmail(someEmail) {
            //Omitted
        },
    }
}
</script>

<template>
    <div>{{isValidEmail('test1@gmail.com')}}</div>
</template>
<script>
import Validators from 'validators.vue'

export default {
    name: 'CompA',
    components: {
        'validators': Validators
    },  
}
</script>

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://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:

export default {
    methods: {
        isValidEmail(someEmail) {
            //Omitted
        }
    }
}

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

<template>
    <div>{{isValidEmail('test1@gmail.com')}}</div>
</template>

<script>
import MixinValidator from 'Validators.js'

export default {
    name: 'CompA',
    mixins: [ MixinValidator ],
}
</script>

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



Source: stackoverflow