JLLMNCHR
JLLMNCHR

Reputation: 1571

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:

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

<template>
    <div>{{isValidEmail('[email protected]')}}</div>
</template>
<script>
import Validators from 'validators.vue'

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

Upvotes: 1

Views: 747

Answers (1)

Dan
Dan

Reputation: 3574

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:

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

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

<template>
    <div>{{isValidEmail('[email protected]')}}</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.

Upvotes: 2

Related Questions