點燈坊

失くすものさえない今が強くなるチャンスよ

Using reactive() to Create the Reactive Object

Sam Xiao's Avatar 2022-11-09

Not only using ref() to create the Reactive Reference, we can also use reactive() to create the Reactive Object.

Version

Vue 3.2

Reactive Object

reactive000

The classical counter is written by reactive()

<template>
  <button @click="onClick">+</button>
  {{ state.count }}
</template>

<script setup>
import { reactive } from 'vue'

let state = reactive({ count: 0 })

let onClick = () => state.count++
</script>

Line 9

let state = reactive({ count: 0 })
  • Use reactive() to define state Reactive Object, count is the property of the Object

Line 11

let onClick = () => state.count++
  • We can read and write directly to state.count without .value

console.log

reactive001

If we use console.log to print out Reactive Object, we will get a Proxy.

<template>
  <button @click="onClick">+</button>
  {{ state.count }}
</template>

<script setup>
import { reactive } from 'vue'

let state = reactive({ count: 0 })

let onClick = () => {
  console.log(state)
  state.count++
}
</script>

Line 11

let onClick = () => {
  console.log(state)
  state.count++
}

Print out the Reactive Object by console.log().

Conclusion

  • Reactive Object is a Proxy and we can access the property directly without .value like Reactive Reference

Reference

SoftAuthor, Must-Know Ref vs Reactive Differences in Vue 3 Composition API