[Vuejs]-Dynamic class concate in v-for loop

2πŸ‘

βœ…

Use binding and a method to return the formatted class name.

Template:
<i :class="getClassName(doc.type)"></i>

Vue –

using a method:

...
methods: {
   getClassName(type){
      return 'fas fa-' + type + ' fa-lg';
   }
}

Or using a computed property:

...
computed: {
   getClassName() {
      return type => `fas fa-${doc.type} fa-lg`;
   }
}

Alternative would be to do something like this (if using ES6+):

<i :class="`fas fa-${doc.type} fa-lg`"></i>
πŸ‘€Jns

1πŸ‘

Try something like this:

<div v-for="doc in documents" :key="doc.id">
  <th></th>
        <th>
            <a href="javascript:void(0)" @click="getChildDocs(doc.id)" :title="doc.type">
                <i :class="{'fas': true, 'fa-file': doc.type == 'file', 'fa-dir': doc.type == 'dir', 'fa-lg': true}"></i>
            </a>
        </th>
        <td>{{ doc.name }}</td>
</div>

Read here https://v2.vuejs.org/v2/guide/class-and-style.html

πŸ‘€Maxim

0πŸ‘

There are many ways to achieve this, here’s one:

data() {
  return {
    iconTypes: {
      'folder': 'fa-folder',
      'file': 'fa-file'
    }
  }
},

methods: {
  executeCommand(doc) {
    if (doc.type === 'file') {
      this.$emit('file-event-handler', any_arguments_here);
      // or simply this.doSomething(doc)
    }

    // or use a switch here
  }

}

<a href="#" @click.prevent="executeCommand(doc)"
  <i class="[ 'fas fa-lg', iconTypes[doc.type] ] "></i>
</a>
πŸ‘€Yom T.

Leave a comment