The Vue Instance & Options API

💚 Vue.js Lesson 2 Beginner

Before Vue 3 introduced the Composition API, components were defined exclusively using the Options API. This approach structures component configuration objects into clear, dedicated option properties.

1 Structure of Options API Properties

The Options API groups component logic based on option categories:

  • data(): A function that returns the component's reactive state properties.
  • methods: An object containing standard class functions and event handlers.
  • computed: An object defining cached, derivative calculations variables.
  • watch: An object containing watcher callbacks to run side effects when reactive variables mutate.
2 Declaring an Options API Component

Let's inspect a standard Single File Component (SFC) layout using the Options API:

Vue — Options Component
<template>
  <div class="counter-card">
    <h3>Counter: {{ count }}</h3>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  // 1. Reactive state definition
  data() {
    return {
      count: 0
    };
  },
  // 2. Class methods
  methods: {
    increment() {
      this.count++;
    }
  },
  // 3. Cached computed properties
  computed: {
    doubleCount() {
      return this.count * 2;
    }
  }
};
</script>
3 Code Challenge
Challenge: Write a new SFC component using the Options API containing a text input field, a data property called message, and a method that prints this message to the console.