首頁  >  問答  >  主體

如何根據方法中的條件隱藏清單元素?

假設我有一個要循環的項目數組,並且每個項目都有自己的基於應用程式其他部分的條件。

<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 天前344

全部回覆(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
  • 取消回覆