Blog>
Snippets

Methods in Options API vs. Composition API

Showcase how methods are created and used in a component with the Options API and how similar logic is implemented with the Composition API.
// Options API example

Vue.component('options-api-methods', {
  data() {
    return {
      count: 0
    };
  },
  methods: {
    increment() {
      this.count += 1;
    }
  },
  template: '<button @click="increment">Increment</button> <span>{{ count }}</span>'
});
In the Options API, methods are defined within the `methods` object. The `increment` method increases the data property `count` by one.
// Composition API example

const { ref, defineComponent } = Vue;

const useCounter = () => {
  const count = ref(0);
  const increment = () => {
    count.value += 1;
  };
  return { count, increment };
};

const compositionApiMethods = defineComponent({
  setup() {
    const { count, increment } = useCounter();
    return { count, increment };
  },
  template: '<button @click="increment">Increment</button> <span>{{ count }}</span>'
});
In the Composition API, logic is encapsulated in a function (`useCounter`) returned from the `setup` function. The `increment` function modifies the reactive `count` reference.