[Vuejs]-How to display icons conditionally using v-for?

3đź‘Ť

âś…

One way would be to add list of icons you want to render and then use the v-for

link to working solution

// data

icons: {
  F: ["gavel"],
  G: ["event"],
  GF: ["gavel", "event"]
},
// template


<td>
  <v-icon v-for="icon in icons[props.item.icon]">{{icon}}</v-icon>
</td>

This way you have nice scalable solution 🙂

2đź‘Ť

You mustn’t use v-if inside v-for. You could filter the array and then iterate.

There is a useful link to Vue best practices
https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential

👤Milesq

0đź‘Ť

Use Vue filters, for further information read from here
https://v2.vuejs.org/v2/guide/filters.html

...
filters: {
  getIcon(value) {
    if (value == "G") {
      return "your icon"
    }
    else if (value == "GF") {
      return "your icon"
    }
    else if (value == "F") {
      return "your icon"
    }
  }
}
...
...
<td> {{ props.item.icon | getIcon}} </td>
...
👤Ahmet Zeybek

0đź‘Ť

I don’t code in Vue but something like this should work, you can use an array for icons & use “icons.map(icon => <>)”etc.

let desserts = [

{
    name: 'ice',
    icon: 'G'
},
{
    name: 'ice2',
    icon: 'E'
},
{
    name: 'ice3',
    icon: 'F'
}

]

let icons = {

val1: '',
val2: '',
val3: ''

};

desserts.forEach((dessert) => {

switch(dessert.icon){
    case 'G':
        icons.val1 = 'http://iconurl'
    case 'E':
        icons.val2 = 'http://iconurl'
    case 'F':
        icons.val3 = 'http://iconurl'
}

})

👤J.C

Leave a comment