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
x
28
28
1
<template>
2
<div></div>
3
</template>
4
<script>
5
export default {
6
name: 'Validators',
7
methods: {
8
isValidEmail(someEmail) {
9
//Omitted
10
},
11
}
12
}
13
</script>
14
15
<template>
16
<div>{{isValidEmail('test1@gmail.com')}}</div>
17
</template>
18
<script>
19
import Validators from 'validators.vue'
20
21
export default {
22
name: 'CompA',
23
components: {
24
'validators': Validators
25
},
26
}
27
</script>
28
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
1
8
1
export default {
2
methods: {
3
isValidEmail(someEmail) {
4
//Omitted
5
}
6
}
7
}
8
Then you can import the mixin in the components you need:
JavaScript
1
13
13
1
<template>
2
<div>{{isValidEmail('test1@gmail.com')}}</div>
3
</template>
4
5
<script>
6
import MixinValidator from 'Validators.js'
7
8
export default {
9
name: 'CompA',
10
mixins: [ MixinValidator ],
11
}
12
</script>
13
In this way, the component CompA
will inherit all the functions, data and computed property defined in the mixin.