v-model 中的空值 [英] Null value in v-model

查看:149
本文介绍了v-model 中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Nativescript-Vue 应用程序,我在其中进行 REST 调用以返回要显示的响应.它可能并不总是完全填充,当发生这种情况时,我会收到一个错误,例如:

I have a Nativescript-Vue app where I make a REST call to return a response to be displayed. It may not always be fully populated, and when that happens I get an error such as:

[Vue 警告]:渲染错误:TypeError: null is not an object(评估'_vm.office.address.addressLine1')"

[Vue warn]: Error in render: "TypeError: null is not an object (evaluating '_vm.office.address.addressLine1')"

这是我从服务器得到的 REST 响应:

Here is the REST response I get from the server:

{
   "officeId":2,
   "name":null,
   "beginDate":[
      2020,
      4,
      18
   ],
   "endDate":null,
   "officeType":null,
   "address":null
}

这里是有问题的Vue代码:

And here is the Vue code that has problems:

<StackLayout class="nt-input">
   <Label text="Address Line 1" class="m-b-5"/>
   <TextField :editable="!isViewOnly" v-model="office.address.addressLine1"  v-shadow="2" hint="Enter address line 1" class="-border"/>
</StackLayout>

因为地址还没有建立,新的记录会为空.有没有办法让它呈现出来以便用户可以填充?

Because the address hasn't been established, it will be null for new records. Is there any way to get this to render so users can populate?

推荐答案

如果 office.address 为空,那么访问 office.address.addressLine1 将始终导致错误.在这样做之前,您必须确保 address 不为空.

If office.address is null, then accessing office.address.addressLine1 will always result in that error. You have to ensure that address is not null before doing so.

获取数据后,您可以检查address是否为空,然后将其设置为您需要的新的空地址对象:

After fetching the data, you can check if address is null and then setting it to a new empty address object that you need:

// Make the request
const office = await fetchOffice()

// Ensure that address is defined
if (!office.address) {
  office.address = {
    addressLine1: ''
  }
}

// Now that we have defined all properties on the object, we
// can assign it to the component instance to make it reactive
this.office = office

在将对象分配给组件之前在对象上定义任何新属性很重要,否则 Vue 不会使新属性具有反应性(阅读 变更检测注意事项).

It is important you define any new properties on the object before you assign it to the component otherwise Vue won't make the new properties reactive (read Change Detection Caveats).

这篇关于v-model 中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆