Sobes.tech
Middle

What is the difference in implementing reactivity between Vue 2 and Vue 3?

sobes.tech AI

Answer from AI

Main differences in reactivity implementation between Vue 2 and Vue 3:

  • Vue 2 uses Object.defineProperty to intercept property changes. This imposes limitations:

    • Cannot detect addition or deletion of properties dynamically.
    • Not always efficient with arrays.
  • Vue 3 switched to using Proxy for reactivity:

    • Allows intercepting all operations on an object, including adding and deleting properties.
    • More performant and flexible mechanism.

Additionally, Vue 3 introduced the Composition API, which is closely related to the new reactive system, allowing creation of reactive objects through reactive and ref functions.

Example of creating a reactive object in Vue 3:

import { reactive } from 'vue';

const state = reactive({ count: 0 });

state.count++;

In Vue 2, reactivity is similarly created automatically when declaring data in a component, but with the limitations described above.