I didn't manage to find much on this, what's the difference between using a method and declaring a function in the script tag?
example.vue
<script>
export default{
methods: {
testfunction1(){
...
}
},
mounted(){
this.testfunction1();
}
}
</script>
compared to
<script>
export default{
methods: {
...
},
mounted(){
testFunction1();
}
}
function testFunction1(){
...
}
</script>
PS: If they're both legit, what are their uses cases? - When to use both?
A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.
methods: they need to run every time to check if the values used withing have changed because they don't know since they are not cached based on their reactive dependencies.. computed properties: they know if the values used in the function changed so they don't need to run every time to check.
Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time.
In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.
Put simply, the testFunction
declared outside of methods
will not have access to the Vue instance via this
.
For example, this will not work
function testFunction() {
console.log(this.someDataProperty)
// "this" is the module scope and someDataProperty will not be defined
}
export default {
data: () => ({ someDataProperty: 'whatever' }),
mounted () {
testFunction()
}
}
If your functions are pure functions, then there's no problem declaring them outside of methods
.
Methods also become part of your component's API so you could have something like this in a parent component
<ChildComponent ref="child"/>
this.$refs.child.someMethod()
Functions declared outside methods
would not be available in this manner.
Another difference mentioned by ssc-hrep3 is that only methods can be called from your component's template
<button @click="someMethod()">Click me!</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With