Vue.js 无法读取 null 的属性“长度" [英] Vue.js Cannot read property 'length' of null

查看:80
本文介绍了Vue.js 无法读取 null 的属性“长度"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

面板不会隐藏.如果我单独检查 socialiteLogins === null 或使用 ==,它们都会返回该对象不为空.不过肯定是空的.如果我将它转储到页面上,我会得到 [] 作为结果.它是一个空的 json 对象.所以如果我试试这个:

面板仍然没有隐藏,我收到此错误:

<块引用>

无法读取 null 的属性 'length'

但是如果我这样做:

<div class="panel panel-default" v-if="socialiteLogins !== null && socialiteLogins.length !== 0">

它完美地隐藏了面板,在初始加载时没有警告,但是当我稍后更新 socialiteLogins 变量时,如果它再次返回空的 json 对象,我会收到长度警告.知道为什么吗?

添加到它...如果我这样做:

它在初始加载时显示,即使没有,但如果我在页面加载后删除它们,它会正确隐藏面板.因此,唯一的问题似乎是初始加载时没有正确检测到没有记录.

解决方案

@RyanZim 的回答有帮助.这是将来其他人通过搜索来到这里的解决方案.

问题源于数据的初始状态.例如,我有这个:

数据:函数(){返回 {社交名流登录:null}},

这适用于 !== null 但不适用于检查 .length.稍后当它返回一个空对象时,.legnth 将起作用但不为空.

所以解决方案是始终保持正确的类型,以便我可以运行一致的检查:

数据:函数(){返回 {社交名流登录:{}}},

对于将来找到此答案的任何人,这里的主要问题是没有使用正确的类型.如果要检查长度,则必须使用数组.对于对象,你会计算键,而不是长度,它不是对象的属性.

If I do this:

<div class="panel panel-default" v-if="socialiteLogins !== null">

The panel doesn't hide. If I check socialiteLogins === null alone, or with ==, they both return that the object isn't null. It's definitely null though. If I dump it on the page, I get [] as the result. It's an empty json object. So if I try this:

<div class="panel panel-default" v-if="socialiteLogins.length !== 0">

The panel still doesn't hide and I get this error:

Cannot read property 'length' of null

But If I do this:

<div class="panel panel-default" v-if="socialiteLogins !== null && socialiteLogins.length !== 0">

It hides the panel perfectly with no warnings on initial load but when I update the socialiteLogins variable later I get the length warning if it ever returns an empty json object again. Any idea why?

Edit:

Adding to it... if I do this:

<div class="panel panel-default" v-show="socialiteLogins">

It shows on initial load even though there are none, but if I remove them after the page loads it properly hides the panel. So the only issue appears to be the initial loading where it's not properly detecting that there are no records.

解决方案

@RyanZim's answer helped. Here's the solution in case anyone else comes here by search in the future.

The issue arises from the initial state of the data. For instance, I had this:

data: function() {
    return {
        socialiteLogins: null
    }
},

Which works for !== null but not for checking .length. Later when it returns an empty object, .legnth will work but not null.

So the solution is keeping it the proper type the entire time so that I can run a consistent check:

data: function() {
    return {
        socialiteLogins: {}
    }
},

Edit: for anyone finding this answer in the future, the main issue here is not using the right type. If you want to check for length, you have to use an array. For objects, you would count the keys, not the length which isn't a property of objects.

这篇关于Vue.js 无法读取 null 的属性“长度"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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