Sobes.tech
Middle

Что такое ref, reactive, computed и watch?

sobes.tech AI

Answer from AI

In Vue.js (and similar reactive frameworks), the following concepts are used for working with reactive data:

  • ref — creates a reactive wrapper for primitive values or objects. Allows tracking changes to the value.

    import { ref } from 'vue';
    const count = ref(0);
    count.value++;
    
  • reactive — creates a reactive object that tracks changes to all its properties.

    import { reactive } from 'vue';
    const state = reactive({ count: 0 });
    state.count++;
    
  • computed — a computed property that automatically recalculates when dependencies change and is cached.

    import { computed } from 'vue';
    const double = computed(() => count.value * 2);
    
  • watch — an observer that monitors changes in reactive data and executes a function when changes occur.

    import { watch } from 'vue';
    watch(count, (newVal, oldVal) => {
      console.log(`count changed from ${oldVal} to ${newVal}`);
    });
    

These tools help manage state and reactivity efficiently in applications.

Что такое ref, reactive, computed и watch? — Frontend - sobes.tech