When it comes to registering functions in Vue Component, my preferred way is to only register methods in the component that are required by the view or need direct access to component data. Other functions that are not needed by the view are kept outside of the Vue component. The assumption here is that utilityFunction()
and utilityFunctionTwo()
are currently only used within this specific component.
Here 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 vary, utility functions can be pure and return values or mutate arguments. There could be various scenarios, but the key is understanding the context of usage.
Another approach 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 may not always need to pass arguments to the method since it has access to the component's data
object.
I personally lean towards the first approach for several reasons:
- I have a concise list of methods that are actually used by the template or required by the component. This helps maintain clarity and organization.
- If a function becomes useful elsewhere in the future, I can easily move it to a separate
.js
file and import it into other components. - Functions do not have unnecessary access to the component's scope if they don't require it.
- It saves me from typing the
this
keyword repeatedly, especially when using lambda functions.
Whether to prefer one approach over the other might be subjective based on personal preferences, but there may also be objective factors to consider such as performance implications or adherence to certain principles of software design.