DEV Community

Nguyen Hoang
Nguyen Hoang

Posted on

Proxy - reactivity vuejs3

let person = {
  name: 'John',
  age: 30
};

let handler = {
  get(target, prop) {
    console.log(`Getting ${prop}`);
    return target[prop];
  },
  set(target, prop, value) {
    console.log(`Setting ${prop} to ${value}`);
    target[prop] = value;
  }
};

let proxyPerson = new Proxy(person, handler);

console.log(proxyPerson.name); // "Getting name" -> "John"
proxyPerson.age = 31; // "Setting age to 31"
console.log(proxyPerson.age); // "Getting age" -> 31
Enter fullscreen mode Exit fullscreen mode

Trong ví dụ trên:

person là một object bình thường.
proxyPerson là một đối tượng "đại diện" cho person được tạo thông qua Proxy.
Khi ta truy cập hoặc thay đổi thuộc tính của proxyPerson, các thao tác này được "lắng nghe" bởi handler, cho phép can thiệp vào những gì xảy ra trước khi trả về hoặc thay đổi giá trị.

Proxy trong Vue 3

Vue 3 sử dụng Proxy để tạo ra hệ thống reactivity. Khi bạn khai báo dữ liệu trong Vue 3 thông qua reactive(), Vue sẽ sử dụng Proxy để theo dõi mọi thay đổi đối với dữ liệu đó.

Ví dụ về reactive() trong Vue 3:


import { reactive } from 'vue';

const state = reactive({
  message: 'Hello, Vue 3!',
  user: {
    name: 'John',
    age: 30
  }
});

console.log(state.message); // 'Hello, Vue 3!'

// Thay đổi giá trị
state.message = 'Hello, Proxy!'; // Vue sẽ tự động cập nhật giao diện

// Thêm thuộc tính mới vào object lồng nhau
state.user.city = 'New York'; // Vue 3 theo dõi thay đổi này

Enter fullscreen mode Exit fullscreen mode

Top comments (0)