Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

Vue/js 先判断一个数组/对象有没有这个字段再判断有没有值

let data = {
    icon: null,
}
let data1 = {
    avatar: '/4399.jpg'
}

代码如上所示,如何用一句代码判断出有icon(或者avatar)这个字段,但icon里没有值,是写在vue的v-if里的

我的错误代码↓

v-if="!data.avatar || !data.Icon"

因为这个data不是固定的,里面有avatar字段的话就没有Icon,所以这样子判断是不行的

在这里先感谢各位大哥大姐的解答了,小弟感激不尽!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

像你那样直接写如果不含该字段会报undefined的错误。要用object的hasOwnProperty()方法判断是否含有该字段。

v-if="data.hasOwnProperty('icon')&&!data.icon"    // 有icon字段但该字段值为null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...