Skip to the workspace
Pebellslearn by building
API Styles  ›  Lesson

The Options API

Options API 12 minThe Options API describes a component as an object of named options such as data, methods and computed, reached through this.

vue / The Options API

Explore each scene at your own pace.

01 · The rule

The rule

The Options API

So far Shelf has used <script setup>. But open almost any Vue 2 codebase, many tutorials, or an older company project, and you meet a different shape: a big object with sections called data, methods and computed. That is the Options API. You will write the Composition API in this course, but you must be able to read this style fluently.

The rule

Options API: one object, labelled drawers, everything reached through this.

Here is a reading-progress counter for a book, written with options:

<script>
export default {
  props: {
    pages: Number
  },
  data() {
    return { pagesRead: 0 }
  },
  computed: {
    percent() {
      return Math.round(this.pagesRead / this.pages * 100)
    }
  },
  methods: {
    addPage() {
      this.pagesRead++
    }
  },
  mounted() {
    console.log('Progress counter is on the page')
  }
}
</script>

<template>
  <p>{{ pagesRead }} / {{ pages }} ({{ percent }}%)</p>
  <button @click="addPage">+1 page</button>
</template>

Each drawer has one job:

  • props declares what the parent passes in.
  • data() is a function that returns the component's reactive state. It must be a function so every instance gets its own fresh object; a shared object would make every counter move together.
  • computed holds values derived from other state.
  • methods holds functions the template and other code can call.
  • Lifecycle options such as mounted run at set moments.

Inside all of them, this is the component instance, so this.pagesRead, this.pages and this.addPage() all work. That is also the trap: write a method as an arrow function, addPage: () => { this.pagesRead++ }, and this no longer points at the component, because arrow functions do not get their own this.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.