What would be preferred way to register functions in Vue Component.
I tend to register in component only methods that are required by view (or require direct component data access) and other functions that are not required by view outside vue component.
The assumption is that utilityFunction()
and utilityFunctionTwo()
are currently used only inside this component.
This is an example:
<template>
<button @click="bar"></button>
<button @click="foo"></button>
<button @click="baz"></button>
</template>
<script>
export default {
name: "SampleComponent",
data() {
return {
someVariable: "ABC",
otherVariable: 123
}
},
methods: {
foo() {
//some logic
utilityFunction(this.someVariable);
//other logic
},
bar() {
//some logic
utilityFunction(this.someVariable);
utilityFunctionTwo(this.otherVariable);
//some other logic
},
baz() {
//some logic
utilityFunctionTwo(this.someVariable);
//some other logic
}
}
}
function utilityFunction(arg){
//do something
}
function utilityFunctionTwo(arg){
//do something
}
</script>
Arguments may be different, utility functions can be pure and return something or mutate argument. There can be a lot of different scenarios. But I hope you have got the point.
The other approach to do it is to add those functions as methods to your component. Like this:
<template>
<button @click="bar"></button>
<button @click="foo"></button>
<button @click="baz"></button>
</template>
<script>
export default {
name: "SampleComponent",
data() {
return {
someVariable: "ABC",
otherVariable: 123
}
},
methods: {
foo() {
//some logic
this.utilityFunction();
//other logic
},
bar() {
//some logic
this.utilityFunction();
this.utilityFunctionTwo(this.otherVariable);
//some other logic
},
baz() {
//some logic
this.utilityFunctionTwo(this.someVariable);
//some other logic
},
utilityFunction() {
//do something
console.log(this.someVariable)
//other stuff
},
utilityFunctionTwo(arg) {
//do something
}
}
}
</script>
In this approach you sometimes don't need to pass argument to method, as it have access to components data
object.
I slightly prefer first approach due reasons:
- I have short list of methods used by template or required by component (for some reason). Sometimes this list can get quite long if all methods are put there.
- If function will be usable elsewhere in the future I will able to easily add it to some
.js
file and import it in other components. - Functions does not have access to components scope if they don't need to
- It saves me from typing
this
keyword ;-) And sometimes might be useful if used inside lambda.
I am not sure if this is a matter of opinion and you can prefer one over the other approach purely by your personal preferences or are they any objective reasons that you should prefer one over the other, like (but not limited to) performance of component or principles of software design that are broken by one solution.