3
votes

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?

2

2 Answers

7
votes

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.

2
votes

Yes, the componsition API is implemented with the setup() method. The usage of setup tells Vue that you want to use the functional approach of the composition API to implement the component.

The Composition API is a set of additive, function-based APIs that allow flexible composition of component logic.

example: how to implement data methods and computed in this functional approach

<template>
  <button @click="increment">
    Count is: {{ state.count }}, double is: {{ state.double }}
  </button>
</template>

<script>
import { reactive, computed } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0,
      double: computed(() => state.count * 2)
    })

    function increment() {
      state.count++
    }

    return {
      state,
      increment
    }
  }
}
</script>

Note: the composition API is also available with Vue.js 2 as plugin (See for more details: https://vue-composition-api-rfc.netlify.com/)