5 min read
•Question 3 of 37mediumHow does Vue reactivity work?
Understanding Vue reactive system with ref and reactive.
What You'll Learn
- ref vs reactive
- How reactivity works
- Reactivity caveats
ref()
For primitive values and single values.
code.jsJavaScript
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // 0
count.value++ // Need .value to access/modifyreactive()
For objects and arrays.
code.jsJavaScript
import { reactive } from 'vue'
const state = reactive({
count: 0,
name: 'Vue'
})
state.count++ // No .value neededHow It Works
Vue 3 uses JavaScript Proxies to track changes:
code.jsJavaScript
// Simplified concept
const state = new Proxy(target, {
get(target, key) {
track(target, key) // Track dependency
return target[key]
},
set(target, key, value) {
target[key] = value
trigger(target, key) // Trigger updates
return true
}
})ref vs reactive
| ref | reactive |
|---|---|
| Primitives & objects | Objects only |
| .value access | Direct access |
| Can reassign | Cannot reassign root |
| Better for single values | Better for state objects |