D2 - Different API styles

Vue components can be authored in two different API styles: Options API and Composition API. Both are perfectly stable and useful production grade web apps. But composition api is popular for its reactivity and reusability.

Options API

With Options API, we define a component's logic using an object of options such as data, methods, and mounted. Properties defined by options are exposed on this inside functions, which points to the component instance:

<script>export default {  // Properties returned from data() become reactive state  // and will be exposed on `this`.  data() {    return {      count: 0    }  },  // Methods are functions that mutate state and trigger updates.  // They can be bound as event listeners in templates.  methods: {    increment() {      this.count++    }  },  // Lifecycle hooks are called at different stages  // of a component's lifecycle.  // This function will be called when the component is mounted.  mounted() {    console.log(`The initial count is ${this.count}.`)  }}</script><template>  <button @click="increment">Count is: {{ count }}</button></template>

Composition API

With Composition API, we define a component's logic using imported API functions. Composition API is typically used with [<script setup>](https://vuejs.org/api/sfc-script-setup.html).

Here is the same component, with the exact same template, but using Composition API and <script setup> instead:

<script setup>import { ref, onMounted } from 'vue'// reactive stateconst count = ref(0)// functions that mutate state and trigger updatesfunction increment() {  count.value++}// lifecycle hooksonMounted(() => {  console.log(`The initial count is ${count.value}.`)})</script><template>  <button @click="increment">Count is: {{ count }}</button></template>

Which to Choose?#

Both API styles are fully capable of covering common use cases. They are different interfaces powered by the exact same underlying system. In fact, the Options API is implemented on top of the Composition API! The fundamental concepts and knowledge about Vue are shared across the two styles.