5
votes

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?

1

1 Answers

8
votes

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>