我有一个 v-if 条件
,如果状态
为未定义
,该条件就会失败。该状态是嵌套的并且非常大(10k+ 条目),并且可能需要时间来构建。必须检查状态的 boolean
类型的 subitem
[0].expand
才能通过 v-if 条件:
v-if="
// condition required to prevent index [0] from failing
(state.priceClassData[type]
? state.priceClassData[type][0].expand
: false)
"
我一直在尝试将其重构为更易于人类阅读的内容。在生产中,一个三元运算符中有多个这样的条件检查,我正在尝试找到一种方法来替换它。
我认为最简单的事情是在 state.priceClassData.type?
上使用 ?
define
运算符,但正如您所看到的,在我的例子中,type
是一个key
,必须像这样调用:
state.priceClassData[type][0]
我在这里没有找到应用 ?
的方法。其他尝试包括计算
:
const checkCondition = computed(() => {
if (state.priceClassData[type] && state.priceClassData[type][0]) {
return state.priceClassData[type][0].expand
}
return false
})
但我找不到将 type
参数传递给它的方法,使其始终返回 true
。我也尝试过普通功能:
function checkCondition(type) {
return (state.priceClassData[type] && state.priceClassData[type][0])
? state.priceClassData[type][0].expand
: false
}
但它似乎只在最初执行,返回false
并且再也不会运行。
我也尝试过组合函数和计算:
const checkCondition = (type) => computed(() => {
return (state.priceClassData[type] && state.priceClassData[type][0])
? state.priceClassData[type][0].expand
: false;
}
始终返回 true 或:
const checkCondition = computed({
get() {
return state.priceClassData
},
set() {
return (state.priceClassData[type] && state.priceClassData[type][0])
? state.priceClassData[type][0].expand
: false;
}
})
它似乎不接受语法。
最佳答案
您可以使用可选链接和无效合并:
state.priceClassData[type]?.[0].expand ?? false
您可以轻松地沿着属性访问链添加更多 ?
,以防止中间值为 null
或 undefined
。
但请注意,对于 v-if
,您实际上并不需要让整个表达式严格等于 false
。 undefined
也是假的,因此如果传递了一个计算结果为 undefined
的表达式,v-if
将不会渲染该元素。因此 v-if="state.priceClassData[type]?.[0].expand"
就足够了。
关于javascript - 有什么方法可以在对象键上使用 'defined' 运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76078435/