假设我有一个要循环的项目数组,并且每个项目都有自己的基于应用程序其他部分的条件。
<template v-for="(item, index) in items">
<li>
<i :class="item.iconClass"></i>
{{ item.name }}
<strong :class="item.textClass"> {{ item.function }} </strong>
</li>
</template>
items: [{
iconClass: "fas fa-calendar",
name: 'item1',
textClass: "text_style",
function: this.function1
},
{
iconClass: "fas fa-user",
name: 'item3',
textClass: "text_style",
function: this.function2
}, {
iconClass: "fas fa-clock",
name: 'item3',
textClass: "text_style",
function: this.function2
}
]
item1 有一个函数,其中包含来自另一个数组的一些数据-
function1() {
if (this.otherArray.otherItem) {
return this.otherArray.otherItem
}
}
现在,如果另一个数组不存在(为 false),则不会显示该数组中的数据,但 item 1 的图标和名称仍将显示,因为它们不属于方法中的条件语句。
那么我该如何重写这个方法,以便在条件为 false 时隐藏列表中的整个项目?
请记住, item 2 和 item 3 有自己的一组条件,因此我无法将 v-if 应用于模板。我需要单独定位这些项目。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
为数组的每个项目添加一个
condition属性-items: [{ iconClass: "fas fa-calendar", name: 'item1', textClass: "text_style", function: this.function1, condition: this.otherArray && this.otherArray.otherItem }, { iconClass: "fas fa-user", name: 'item3', textClass: "text_style", function: this.function2, condition: true // you can write your logic here }, { iconClass: "fas fa-clock", name: 'item3', textClass: "text_style", function: this.function2, condition: true // you can write your logic here } ]并在
模板中,使用此属性来隐藏/显示项目-<template v-for="(item, index) in items"> <li v-if="item.condition"> <i :class="item.iconClass"></i> {{ item.name }} <strong :class="item.textClass"> {{ item.function }} </strong> </li> </template>