問題發生場景
在vue3中使用reactive響應式轉換一個帶有私有屬性的物件。
大致原因
在js中,代理Proxy和類的私有屬性無法公用,而vue3的響應式是基於代理的。
簡單例子
function logReads(target) {
return new Proxy(target, {
get(obj, prop, receiver) {
console.log(prop);
return Reflect.get(obj, prop, receiver)
},
});
}
class TodoList {
#items = [];
threshold = 50;
countCheap() {
return this.#items.reduce((n, item) => item.price < this.threshold ? n : n + 1, 0);
}
}
let list = logReads(new TodoList());
list.countCheap(); // TypeError: Cannot read private member #items from an object whose class did not declare it
github上的討論
https://github.com/tc39/proposal-class-fields/issues/106