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:
propsdeclares 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.computedholds values derived from other state.methodsholds functions the template and other code can call.- Lifecycle options such as
mountedrun 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.
The shortcut
When you read an Options component, sort each name by its drawer: is it state (data), input (props), derived (computed) or action (methods)? Then any this.something tells you where to look.
Find the handler
The template says
@click="addPage". Look inmethods: there it is.
Drills
Answer fast — trust the rule.
Why must data be a function that returns an object?
In the Options API, how does a method read the pagesRead state?
methods: { addPage: () => { this.pagesRead++ } } does not update the counter. Why?
Which drawer should hold "percentage of the book read", calculated from other state?
Remember
- The Options API groups code into
props,data,computed,methodsand lifecycle options. - Shortcut: sort each name by its drawer;
this.xtells you where to look. - Trap: arrow functions as methods lose
this;dataas a plain object shares state.
