Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Vue3's Ref and Reactive for State Management

Tech 1

Vue3 introduces two fundamental reactivity APIs: ref and reactive. These tools enable developers to create responsive data structures efficiently.

1. Core Concepts

1.1 Ref API

ref creates a reactive reference to a primitive value:

import { ref } from 'vue';

const counter = ref(0);
console.log(counter.value); // Access value
counter.value++; // Modify value

1.2 Reactive API

reactive makes entire objects responsive:

import { reactive } from 'vue';

const user = reactive({
  name: 'John',
  age: 25
});
console.log(user.name); // Access property
user.age++; // Modify property

2. Practical Implementations

2.1 Using Ref with Side Effects

import { ref, watchEffect } from 'vue';

const count = ref(0);

watchEffect(() => {
  console.log(`Current count: ${count.value}`);
});

2.2 Reactive Object Monitoring

import { reactive, watchEffect } from 'vue';

const profile = reactive({
  username: 'dev123',
  loggedIn: false
});

watchEffect(() => {
  console.log(`User status: ${profile.loggedIn ? 'Online' : 'Offline'}`);
});

3. Advanced Patterns

3.1 Ref in Component Lifecycle

import { ref, onMounted } from 'vue';

const timer = ref(null);
const seconds = ref(0);

onMounted(() => {
  timer.value = setInterval(() => {
    seconds.value++;
  }, 1000);
});

3.2 Nested Reactive Structures

import { reactive } from 'vue';

const store = reactive({
  user: {
    preferences: {
      theme: 'dark'
    }
  },
  settings: {
    notifications: true
  }
});

console.log(store.user.preferences.theme);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.