6

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?

0

1 Answer 1

9

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>
Sign up to request clarification or add additional context in comments.

5 Comments

Right! Great point. So will there be a use case for non-method functions? Should I separate them as "helper" functions if they do not need access to this and only include them in methods as required? Underlying question - What would be a good/more correct way to structure my code?
That's how I've used them in the past, ie helpers, utility, etc. It's pretty subjective but if you want to keep your component's API clean, moving junk out of methods is one way to do so. It might also help with unit testing if you can test your helper functions in isolation
You can also directly use the method in the same component's template: <div @click="someMethod()"></div> and even pass inline variables of a v-for as method parameters: <div v-for="item in list"><div @click="someMethod(item)"></div></div>
@ssc-hrep3 excellent point. If you don't mind, I'll add that to the answer
Just go for it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.