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
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 definestate
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
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