0

I'm currently learning Vue 3 and the Composition API, and I'm wondering what the recommended way of defining a function is using the Composition API. In the official Vue 3 documentation, I noticed that they use regular functions to define methods and event handlers, like this:

import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const message = 'Hello Vue!'
    const handleClick = function(event) {
      console.log(event.target)
    }
    return {
      message,
      handleClick
    }
  }
})

However, I've also seen examples online that use arrow functions instead, like this:

import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const message = 'Hello Vue!'
    const handleClick = (event) => {
      console.log(event.target)
    }
    return {
      message,
      handleClick
    }
  }
})

I know that both approaches are valid, but I'm wondering if there's a recommended way of doing it using the Composition API, or if it's mostly a matter of personal preference. Are there any benefits or drawbacks to using one approach over the other? Does it depend on the specific use case or context?

Any insights or advice would be greatly appreciated. Thank you in advance!

KevDev
  • 541
  • 2
  • 6
  • 20
  • 4
    Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – Reyno Apr 11 '23 at 14:36
  • @Reyno I am aware of the differences of the arrow function and regular function on my question I just want to know what is the recommended way of doing it on a vue3 composition api. Thanks though it is a good read.. – KevDev Apr 11 '23 at 14:46
  • the intrisic differences are the only differences. there are no Vue specific benefits or negatives to using either. – yoduh Apr 11 '23 at 15:19
  • @KevDev You still write in JS, so the same concerns are applicable as in dupe question. Since you aware that `this` isn't used with composition api, there's no practical difference besides the extra characters – Estus Flask Apr 11 '23 at 15:47
  • There is no recommended way of defining a function in Vue 2/3. – Tolbxela Apr 12 '23 at 07:44
  • Only significant difference is that in error call stack you won't see function name, only `{anonymous}()` – Leon Apr 15 '23 at 05:33
  • One recommendation is, to use the same approach everywhere in the project. Just decide for one and be consistent – Leif Marcus Apr 15 '23 at 10:40

0 Answers0