【发布时间】:2021-09-09 22:50:52
【问题描述】:
我试图在一个类中拥有一个反应性属性,所以这就是我所做的:
Class B{
index = ref(-1);
canUndo: ComputedRef<boolean>;
canRedo: ComputedRef<boolean>;
constructor(private max: number) {
this.canUndo = computed(() => {
return this.index.value > -1;
});
this.canRedo = computed(() => {
const { length } = this.items;
return length > 0 && this.index.value < length - 1;
});
}
undo() {
console.log(this.canUndo); // -> true
console.log(this.canUndo.value); // -> undefined
if (!this.canUndo.value) return false;
console.log(this.index); // -> 1
this.index.value -= 1;
return this.items.slice(0, this.index.value + 1);
}
}
// this is how I use it
class A{
b:B;
undo(){ this.b.undo() }
}
export default defineComponent({
setup(){
const a= ref<A>();
function initA() {
a.value = new A();
}
return { a };
}
});
<BaseButton
:disabled="!a.b.canUndo"
color="light" size="sm" @click="a.undo()"
start-icon="undo"></BaseButton>
我原以为这会起作用,但我看到了一个奇怪的行为!this.canUndo 是 boolean,我预计是 ComputedRef<boolean>,因此 this.canUndo.value 是 undefined!
this.index?!? 也是如此?
为什么?难道我做错了什么?这是一个错误吗?
根据@tony19 的回答更新: 组件其实是这样的:
export default defineComponent({
setup(){
const elRef = ref<HTMLElement>();
const a = ref<A>();
function initA() {
a.value = new A(elRef);
}
onMounted(initA);
return { a };
}
});
我无法执行任何建议的解决方法因为我需要一个元素 ref 来实际启动类,所以它需要在 onMounted 钩子中启动。
【问题讨论】:
标签: javascript typescript vue.js vuejs3 vue-reactivity