search

Home  >  Q&A  >  body text

How to hide list elements based on condition in method?

Suppose I have an array of items that I want to loop through, and each item has its own condition based on other parts of the application.

<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 There is a function that contains some data from another array -

function1() {
  if (this.otherArray.otherItem) {
    return this.otherArray.otherItem
  }
}

Now, if the other array does not exist (is false), the data in that array will not be displayed, but the icon and name of item 1 will still be displayed because they do not belong in the method Conditional statements.

So how can I override this method so that the entire item in the list is hidden when the condition is false?

Keep in mind that item 2 and item 3 have their own set of conditions, so I can't apply v-if to the template. I need to target these items individually.

P粉215292716P粉215292716329 days ago367

reply all(1)I'll reply

  • P粉715304239

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

    Add a condition attribute to each item of the array-

    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
      }
    ]

    And in template, use this property to hide/show items-

    <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>

    reply
    0
  • Cancelreply