Skip to content

Vue 3: Advanced Reactivity

Vue 3's reactivity system is completely rewritten and based on JavaScript Proxy for superior performance.

How Reactivity Works

Vue 3 uses Proxy instead of Object.defineProperty (used in Vue 2):

javascript
import { ref, reactive } from 'vue'

// ref for primitive values
const count = ref(0)

// reactive for objects
const state = reactive({
  user: { name: 'Mario', email: 'mario@example.com' },
  settings: { theme: 'dark' }
})

Computed Properties

Computed properties are cached and only recalculate when dependencies change:

vue
<script setup>
import { ref, computed } from 'vue'

const items = ref([1, 2, 3, 4, 5])

const total = computed(() => {
  return items.value.reduce((sum, item) => sum + item, 0)
})

const evenItems = computed(() => {
  return items.value.filter(item => item % 2 === 0)
})
</script>

Advanced Watchers

javascript
import { ref, watch } from 'vue'

const query = ref('')
const results = ref([])

// Watch with deep option
watch(state, (newVal, oldVal) => {
  console.log('State changed:', newVal)
}, { deep: true })

// Multiple watch
watch([query, results], ([newQuery, newResults]) => {
  console.log('Query:', newQuery, 'Results:', newResults.length)
})

Conclusion

Understanding reactivity is essential for writing efficient and performant Vue applications.

Made with ❤️ by PeterDev
'Ho mio cuGGGino che lo sa fare' cit.