问题
I have a ref
:
const editItem = ref<object | null>(null)
Here's an example value for it:
{
id: 1,
title: 'Harry Potter',
author: 'J.K. Rowling',
created: '30-08-2000',
}
If I run console.log(editItem.value)
, I see this object:
But when I try to read the value's author
with console.log(editItem.value.author)
, then I see this error:
Object is possibly 'null'.
回答1:
Since the type of the ref is object | null
, it could be null
when you access it, leading to a runtime exception. The error message is warning about that possibility for editItem.value
.
You could either add a null
-check around its access:
if (editItem.value) {
console.log(editItem.value.author)
}
...or you could simply use optional chaining:
console.log(editItem.value?.author)
But you'll notice that you'll get a different warning about author
not being part of the signature for object
. One solution is to change the ref
's type from object
to a specific interface:
interface MyRef {
id: number;
title: string;
author: string;
created: string;
}
const editItem = ref<MyRef | null>(null)
console.log(editItem.value?.author) ✅
回答2:
Cześć Michal
The issue (without seeing the code) seems to be that you are using ref for a object value. While you may find some workaround to get it to work, the simplest way to deal with reactive objects is to use reactive
instead of ref
.
One additional benefit is that you won't need to use .value
when you're getting or setting the object value.
来源:https://stackoverflow.com/questions/64613226/vue-3-composition-api-get-value-from-object-ref