我声明了两个类。
Goods
和 User
class Goods {
#price: number
#quantity: number
constructor(price: number, quantity: number) {
this.#price = price;
this.#quantity = quantity;
}
get totalPrice() {
return this.#price * this.#quantity;
}
totalPriceFunc() {
return this.#price * this.#quantity;
}
}
class User {
private id: number
private name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
get info() {
return `id: ${this.id}, name: ${this.name}`;
}
infoFunc() {
return `id: ${this.id}, name: ${this.name}`;
}
}
init
Goods
和 User
并使用 vue3 ref
;
const g = new Goods(10, 100);
console.log('>>>>>>>g ref before: ', g.totalPrice, g.totalPriceGetFunc());
// >>>>>>>g ref before: 1000 1000
const gRef = ref<Goods>(g);
console.log('>>>>>>>g ref after: ', g.totalPrice, g.totalPriceGetFunc());
// >>>>>>>g ref after: 1000 1000
try {
console.log('gRef totalPrice: ', gRef.value.totalPrice);
console.log('gRef totalPriceGetFunc: ', gRef.value.totalPriceGetFunc());
} catch (e) {
console.error(e);
// TypeError: Cannot read private member #price from an object whose class did not declare it
// at get totalPrice (HelloWorld.vue:19:15)
// at Reflect.get (<anonymous>)
// at MutableReactiveHandler.get (reactivity.esm-bundler.js:928:25)
// at setup (HelloWorld.vue:50:46)
// at callWithErrorHandling (runtime-core.esm-bundler.js:199:19)
// at setupStatefulComponent (runtime-core.esm-bundler.js:7847:25)
// at setupComponent (runtime-core.esm-bundler.js:7808:36)
// at mountComponent (runtime-core.esm-bundler.js:5161:7)
// at processComponent (runtime-core.esm-bundler.js:5127:9)
// at patch (runtime-core.esm-bundler.js:4645:11)
}
-------------------------------------------------------------------
const u = ref<User>(new User(1, 'Daniel'));
console.log('u info: ', u.value.info);
// u info: id: 1, name: Daniel
console.log('u infoFunc: ', u.value.infoFunc());
// u infoFunc: id: 1, name: Daniel
为什么使用
#price
声明响应状态时,Goods
的ref
属性无法使用,而private id private name
却可以正常使用?
Vue 中的原始值(例如
#price
)不会成为“响应式”,因为 ref 仅跟踪公共属性。这就是 Vue 框架的本质。
当您使用“
private
”时它会起作用,因为它来自 TypeScript,而不是 Vue。这是所谓的“编译时注释”,因此不会在运行时强制执行。