vue 前端对null的处理,项目中使用v-if判断数组长度是,length报错?

说明:以前做服务器开发的时候,前端人员总是说,不要传null过来,不要传null过来,传“”空字符串过来都可以。当时就想,为啥不能传null,你前端做下判断不就行了吗。

没想到现在自己既开发前端,又开发后台,就遇到了这个问题。

其实真的就是坐下 !=null就可以了。

例子

<span>{{changeRemarkLength(scope.row.remark)}}</span>

<script>
computed:{
    changeRemarkLength(){
                return function (text) {    
                    if(text.length > 14){ 
                        return text.slice(0,14)+"...";
                    }else{
                        return text;
                    }
                }
            },
}
</script>

在vue中用一个计算属性改变  remark:备注  文本的显示格式。如果字符长度大于14,之后的字符用。。。t代替。

但是如果后台传的是  remark为null,那这里就会报 : v-if判断数组长度是,length报错

[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of null"

解决:在判断之前在判断下 !=null就行了

<script>
        changeRemarkLength(){
                return function (text) {
                    if(text!=null && text.length > 14){ 
                        return text.slice(0,14)+"...";
                    }else{
                        return text;
                    }
                }
        },
</script>

猜你喜欢

转载自blog.csdn.net/weixin_40841731/article/details/83821542