【问题标题】:Vue 3 composition API get value from object refVue 3 组合 API 从对象 ref 获取值
【发布时间】:2021-02-13 04:51:00
【问题描述】:

我有一个ref:

const editItem = ref<object | null>(null)

这是它的一个示例值:

{
   id: 1,
   title: 'Harry Potter',
   author: 'J.K. Rowling',
   created: '30-08-2000',
}

如果我运行console.log(editItem.value),我会看到这个对象:

但是当我尝试用console.log(editItem.value.author) 读取值的author 时,我看到了这个错误:

Object is possibly 'null'.

【问题讨论】:

标签: typescript ref vuejs3 vue-composition-api


【解决方案1】:

由于 ref 的类型是object | null,当你访问它时它可能是null,导致运行时异常。错误消息警告editItem.value 的这种可能性。

您可以添加一个null-检查其访问权限:

if (editItem.value) {
  console.log(editItem.value.author)
}

...或者你可以简单地使用optional chaining:

console.log(editItem.value?.author)

但是您会注意到,您会收到关于author 不是object 签名的一部分的不同警告。一种解决方案是将ref 的类型从object 更改为特定接口:

interface MyRef {
  id: number;
  title: string;
  author: string;
  created: string;
}

const editItem = ref<MyRef | null>(null)

console.log(editItem.value?.author) ✅

【讨论】:

    【解决方案2】:

    切希奇·米哈尔

    问题(没有看到代码)似乎是您将 ref 用于对象值。虽然您可能会找到一些解决方法来使其工作,但处理反应性对象的最简单方法是使用 reactive 而不是 ref。

    另一个好处是您在获取或设置对象值时不需要使用.value。

    【讨论】:

    • 谢谢,这解决了我面临的一个问题。 Vue.js 文档中不够清楚。
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2022-06-29
    • 2022-12-09
    • 2020-11-11
    • 2020-05-28
    相关资源
    最近更新 更多