Vue 3 composition API get value from object ref

怎甘沉沦 提交于 2021-02-11 12:49:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!