简体   繁体   English

Vue 3 - Typescript - 对象可能为空问题

[英]Vue 3 - Typescript - Object is possibly null issue

I checked other threads but couldn't find the solution.我检查了其他线程,但找不到解决方案。

setup() {
  const processingData = ref(null)
}

Function:功能:

function create() {
  let field = JSON.parse(processingData.value.fields)

  for (let i = 0; i < field.length; i++) {
    console.log(i)
  }
}

Error on JSON.parse(processingData.value.fields): Object is possibly 'null'.Vetur(2531) const processingData: Ref<null> JSON.parse(processingData.value.fields) 上的错误: Object is possibly 'null'.Vetur(2531) const processingData: Ref<null>

processingData is 100% accessable, as It's being set with another function already. processingData 是 100% 可访问的,因为它已经被另一个函数设置了。

In Typescript there is a Non-null assertion operator you can add to let your code know that the value won't be null when your using it:在 Typescript 中,您可以添加一个非空断言运算符,让您的代码知道在使用它时该值不会为空:

let field = JSON.parse(processingData.value!.fields)

This should help.这应该有帮助。 But as I see your processingData has no type.但正如我所见,您的 processingData 没有类型。 This will lead to another problem.这会导致另一个问题。 TS can't find the property fields. TS 找不到属性字段。 So either parse it as any or add the type to your ref.因此,要么将其解析为 any,要么将类型添加到您的 ref 中。

ref type:参考类型:

setup() {
  const processingData: Ref<{ fields: any }> = ref({fields: null})
}
...
let field = JSON.parse(processingData.value!.fields)

or parse it as any like:或者像这样解析它:

let field = JSON.parse((processingData.value as any).fields)

Otherwise you can logically make sure that the value is not null.否则,您可以在逻辑上确保该值不为空。

if(processingData.value){
  field = JSON.parse(processingData.value.fields) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM