javascript - 类中的vue3反应性
问题描述
我试图在一个类中拥有一个反应属性,所以这就是我所做的:
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
钩子中启动。
解决方案
我认为这与ref
s 如何在模板中自动展开有关,如setup()
docs中所述。这似乎包括ref
在类的方法中展开 s 。
一种解决方法是将原始实例公开给模板。它不需要是 a ref
,除非您计划更改它的值(例如,更改为 的新实例A
):
export default defineComponent({
setup() {
//const a = ref<A>(new A())
const a = new A()
return { a }
}
})
如果您确实需要保留 a ref
,则可以将aref
与原始文件一起公开:
export default defineComponent({
setup() {
const rawA = new A()
const a = ref<A>(rawA)
return { a, rawA }
}
})
然后在您的模板中,将原始用于任何具有ref
s 的方法:
<BaseButton @click="rawA.undo()">
推荐阅读
- node.js - MongoDB:如何从数据库中获取最后一项?
- c++ - 使用 C++ 在不丢失前导 0 的情况下转换二进制 char 数组
- django - Django Form Is Valid 不产生任何错误但返回 False
- sql - 如何使用 uniq ganantee 在 Tarantool DB 中获取 1 条记录?
- html - 不能更改 css 中的任何内容
- node.js - 尝试运行 ESLint 脚本时出现“SyntaxError: Unexpected token {”
- email - 尝试使用 MailListener Protractor/Jasmine 端到端测试检索发送到 gmail 帐户的代码时出错
- visual-studio - 发布时 Visual Studio 2019 Azure KeyVault 配置错误
- javascript - 使用 HTML 和 javascript 下载第三方 pdf 链接
- kubernetes - 如何获取从 helm chart 填充所有值的清单文件?