Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use setup() hook of Vue Composition API

As the composition api of Vue has ported for the current version, v2, apparently we can start to use it before the release of the new version.

The examples generally feature a newly introduced setup() hook, and it is depicted alone and or along with basic JS functions.

At first glance I thought it is simply a place for initializing reactive data and I'd ask sth like: in what cases should it be used.

However, when you dig more, it looks as if composition API cannot be implemented without it. So, what is the thing with that hook and can it be used with data, methods, computed etc. fields outside it?

like image 362
vahdet Avatar asked Oct 16 '19 17:10

vahdet


People also ask

What is script setup in Vue?

<script setup> <script setup> is a compile-time syntactic sugar for using Composition API inside Single-File Components (SFCs). It is the recommended syntax if you are using both SFCs and Composition API. It provides a number of advantages over the normal <script> syntax: More succinct code with less boilerplate.

How do you pass props in composition API?

In <script setup> for ChildComponent. vue, set the state of isShowing in the TransitionRoot HeadlessUI component to true. Use defineProps to handle the passing of the show prop into ChildComponent. Deconstruct the prop using toRefs().

What is REF () in Vue?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.


Video Answer


1 Answers

The composition API is really another way to do the same thing as before. Mainly:

  • The local state in data is replaced by a call to reactive.
  • Hooks mounted, beforeDestroy, etc. are replaced by subscriptions to onMounted, onUnmounted etc.
  • Declarations in watch are replaced by calls to watch.
  • computed properties are replaced by a call to computed in an object passed to reactive.
  • The setup function returns an object that contains a composition of all the things that have to remain accessible from outside the setup function, in particular from the template. And this feature replaces old methods.

I'd ask sth like: in what cases should it be used.

Nothing is deprecated, so you have now two ways to do the same thing and nothing prevents you from mixing if you want. Nothing except the composition API is better than the old way. And once you adopt it, you will completely abandon the old way of doing things.

See also: The motivation of the Vue's creator.

like image 136
Paleo Avatar answered Oct 11 '22 01:10

Paleo