v-model 中的空值
Null value in v-model
我有一个 Nativescript-Vue 应用程序,我在其中对 return 进行 REST 调用以显示响应。它可能并不总是完全填充,当发生这种情况时,我会收到如下错误:
[Vue warn]: Error in render: "TypeError: null is not an object
(evaluating '_vm.office.address.addressLine1')"
这是我从服务器获得的 REST 响应:
{
"officeId":2,
"name":null,
"beginDate":[
2020,
4,
18
],
"endDate":null,
"officeType":null,
"address":null
}
这里是有问题的 Vue 代码:
<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>
因为地址还没有建立,所以对于新的记录来说是空的。有什么方法可以渲染它以便用户填充?
如果 office.address
为空,则访问 office.address.addressLine1
将始终导致该错误。在这样做之前,您必须确保 address
不为空。
获取数据后,您可以检查address
是否为空,然后将其设置为您需要的新空地址对象:
// 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 不会使新属性具有反应性(阅读 Change Detection Caveats ).
我有一个 Nativescript-Vue 应用程序,我在其中对 return 进行 REST 调用以显示响应。它可能并不总是完全填充,当发生这种情况时,我会收到如下错误:
[Vue warn]: Error in render: "TypeError: null is not an object (evaluating '_vm.office.address.addressLine1')"
这是我从服务器获得的 REST 响应:
{
"officeId":2,
"name":null,
"beginDate":[
2020,
4,
18
],
"endDate":null,
"officeType":null,
"address":null
}
这里是有问题的 Vue 代码:
<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>
因为地址还没有建立,所以对于新的记录来说是空的。有什么方法可以渲染它以便用户填充?
如果 office.address
为空,则访问 office.address.addressLine1
将始终导致该错误。在这样做之前,您必须确保 address
不为空。
获取数据后,您可以检查address
是否为空,然后将其设置为您需要的新空地址对象:
// 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 不会使新属性具有反应性(阅读 Change Detection Caveats ).