首页  >  问答  >  正文

如何根据方法中的条件隐藏列表元素?

假设我有一个要循环的项目数组,并且每个项目都有自己的基于应用程序其他部分的条件。

<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 2item 3 有自己的一组条件,因此我无法将 v-if 应用于模板。我需要单独定位这些项目。

P粉215292716P粉215292716282 天前348

全部回复(1)我来回复

  • P粉715304239

    P粉7153042392024-01-11 11:42:50

    为数组的每个项目添加一个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>

    回复
    0
  • 取消回复