在vue或者js中,使用.length的时候在浏览器的控制台中经常会报TypeError: Cannot read property 'length' of undefined的错误,类似的错误还有很多,大多都是TypeError: Cannot read property 'xxx' of undefined,出现这种错误的原因很简单,就是你调用该方法或函数的字符串或数组、对象等等出现了为空的情况,加一个判断就好了。

例子:
下面的代码会报TypeError: Cannot read property 'length' of undefined的错误

let txtDom = this.$refs.textContainer;
for (let i = 0; i < txtDom.length; i++) {
       let curHeight = txtDom[i].offsetHeight;
       if (curHeight > twoHeight) {
           this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
       } else {
           this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
       }
}

原因就是txtDom出现了为空的情况,所以就没有length的属性了。解决方法就是判断txtDom是否为空,如下:

let txtDom = this.$refs.textContainer;
if(txtDom){
     for (let i = 0; i < txtDom.length; i++) {
         let curHeight = txtDom[i].offsetHeight;
         if (curHeight > twoHeight) {
             this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
         } else {
             this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
         }
     }
 }

上面是在js中的代码报错,有时候我们在html中也会使用一些函数或方法,也要做判断,如下al.time是从后端读取的数据,可能会为空,会报TypeError: Cannot read property 'substring()' of undefined的错误:

<el-tag size="mini"   v-if="al.time">发布时间</el-tag>{{ al.time.substring(0,10)}}

解决方法是使用三元运算符做判断:

<el-tag size="mini"   v-if="al.time">发布时间</el-tag>{{ al.time ? al.time.substring(0,10):al.time}}

这样就可以完美解决问题了。

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐