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?
<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.
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().
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.
The composition API is really another way to do the same thing as before. Mainly:
data
is replaced by a call to reactive
.mounted
, beforeDestroy
, etc. are replaced by subscriptions to onMounted
, onUnmounted
etc.watch
are replaced by calls to watch
.computed
properties are replaced by a call to computed
in an object passed to reactive
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With