How to hide list elements based on condition in method?
P粉215292716
P粉215292716 2024-01-10 17:11:49
0
1
342

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粉215292716
P粉215292716

reply all(1)
P粉715304239

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!