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.