Home > Mobile >  Why should I still add function keyword when I configured a vue3 project with Typescript support?
Why should I still add function keyword when I configured a vue3 project with Typescript support?

Time:12-05

I come from Angular background, and in which we don't use the function keyword when we declare methods inside a component. This is because I'm using TypeScript which is ECMAScript6 compliant.

Now, I'm learning vue3 (composition API) with TypeScript enabled.

But if I omit the function keyword when declaring events inside a component, it's not being recognized and the compiler is throwing an error.

I'm trying to understand why is this difference but unable to figure out. Thank you for your help in making me understand the concepts.

// Doesn't work
updateName(fName: string, lName: string) {}

// works
function updateName(fName: string, lName: string) {}

CodePudding user response:

In Angular, we define methods in a class-based component:

@Component()
class MyAngularComponent {
  // Method inside a class
  myClassMethod() {}
}

This uses the ES6 method definition in a class.

But in Vue 3 Composition API, we just write and call a script, there is no longer a wrapping object (like in Vue 2 Options API) or class (like in vue-class-component, Angular or React class-based components):

<script setup>
// No wrapping object or class
// Functions are directly in the script body
function someHelperFunction() {}
</script>

Therefore the programming language syntax (whether JavaScript or TypeScript) does not allow the method definition syntax in this case.

  • Related