Nerd For Tech
Published in

Nerd For Tech

Composition API: The need to know basics and 3 things to keep in mind.

Vue 3 miniseries

🤔 But WHY???

Options API example
Not mine. This is Vue’s.

👾Ok, so HOW?

<!-- MyComponent.vue -->
<template>
<h1>Title</h1>
<div>Hello, my name is {{ name }}, and I'm {{ age }} years old.</div>
</template>

<script>
export default {
setup() {
let name = 'Pato'
let age = 35

// Return the properties so they can be accessed by template
return {
name,
age
}
}
}
</script>

⚠️ 3 Things to keep in mind

  1. The values declared on setup() are NOT reactive by default. As you may remember, on Options API the data object converts its properties into getter/setters to make them reactive, and hence whenever we made a change, it would be reflected on the DOM. On setup(), in order to reflect changes, you will need to make sure the value is reactive by using either Ref or Reactive.
  2. The “this” keyword is not available inside setup(). On Options API the “this” keyword refers to the component, but on Composition API “this” will be undefined. Because setup() is called before any other lifecycle hook, “this” won’t be a reference to the current active instance and therefore will not behave as in other options.
  3. Setup() must return an object whenever you want the component’s template to access the properties of the context, as well as the ones of props passed into setup(). Whichever property from setup() that you want to use in the component’s template, needs to be returned in a JS object.
The example is not mine, it’s from the Vue docs. Here is the link.

🤩In summary…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pato Montecchiarini

I’m a web & mobile developer. Love all CSS related things. Coding in JS and Dart.