vue3+typescript,v-for取对象的某个列表属性,其中这个对象可能为空,列表属性也可能为空,要怎么判断
时间: 2024-05-07 08:17:31 浏览: 9
你可以使用可选链接运算符 `?.` 和空值合并运算符 `??`,比如这样:
```html
<template>
<div>
<div v-for="item in itemsWithProperty" :key="item.id">
{{ item.property?.nestedProperty ?? 'N/A' }}
</div>
</div>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
data() {
return {
items: [
{ id: 1, property: { nestedProperty: 'value' }},
{ id: 2, property: null },
{ id: 3, property: { nestedProperty: null }},
{ id: 4, property: { }},
{ id: 5 },
{ id: 6, property: undefined },
],
};
},
computed: {
itemsWithProperty() {
return this.items.filter((item) => item.property != null);
},
},
});
</script>
```
在这个例子中,我们通过过滤出存在 `property` 的 `items` 来避免出现空对象的情况。对于可能为空的属性的取值,使用了可选链接运算符 `?.`,它在左侧的表达式为 `null` 或 `undefined` 时直接返回 `undefined`,避免了因为属性不存在而抛出异常。最后,使用了空值合并运算符 `??`,在左侧的表达式为 `null` 或 `undefined` 时返回右侧的默认值 `'N/A'`,避免了空属性值的情况。