Frontend
1 min read
#vue #composition-api #reactive

Creating component state like Options API using reactive()

In Options API we can use data() function to create a state for the component, then access it directly via this.

Using reactive() from Composition API achieves the same pattern — much easier than using ref() for multiple state properties.

<script>
import { computed, reactive, toRefs } from 'vue'

export default {
  setup() {
    const state = reactive({
      price: 2,
      quantity: 5
    })

    const total = computed(() => {
      return state.price * state.quantity
    })

    return {
      ...toRefs(state),
      total
    }
  }
}
</script>

<template>
  <p>Price: {{ price }}</p>
  <p>Quantity: {{ quantity }}</p>
  <p>Total: {{ total }}</p>
</template>