Blog>
Snippets

Creating computed properties

Show the difference in creating computed properties with the Options API's computed option and the Composition API's computed function.
// Using Vue.js 2 with Options API
new Vue({
  el: '#app',
  data: {
    a: 1,
    b: 2
  },
  computed: {
    // a computed property for sum of a and b
    sum: function() {
      return this.a + this.b;
    }
  }
});
This example uses Vue 2 with the Options API to create a computed property called 'sum' within a Vue instance. The 'sum' property will automatically update whenever `a` or `b` changes.
// Using Vue.js 3 with Composition API
import { reactive, computed } from 'vue';

setup() {
  const state = reactive({ a: 1, b: 2 });

  // a computed property for sum of state.a and state.b
  const sum = computed(() => state.a + state.b);

  return { state, sum };
}
In this example using Vue 3 with the Composition API, a reactive state is created with properties 'a' and 'b'. A computed property 'sum' is then created using the 'computed' function, which will return the sum of `state.a` and `state.b`. The computed property 'sum' along with the 'state' is returned from the `setup` function and can be used in the template.