Combining dynamic classes within a v-for loop

Here's my custom for loop:

      <div v-for="document in documents">
        <span></span>
        <span><a href="javascript:void(0)" @click="displayChildDocs(document.id)" :title="document.type"><i class="fas fa-{{ document.type }} fa-lg"></i></a></span>
        <p>{{ document.name }}</p>
      </div>

I have a unique doc.type attribute that can be either folder or file. I'm looking to dynamically change the FontAwesome icon by concatenating 'fa-' with the doc.type value. Can this be done successfully?

Answer №1

Implement a binding system along with a method that will provide the formatted class name.

Template:

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

Vue -

utilizing a method:

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

Alternatively, you can use a computed property:

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

An alternative approach could be something like this (if utilizing ES6+):

<i :class="`fas fa-${doc.type} fa-lg`"></i>

Answer №2

Consider using a structure similar to the one below:

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

For more information, refer to https://v2.vuejs.org/v2/guide/class-and-style.html

Answer №3

Here's a solution for achieving this task:

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

methods: {
  processAction(item) {
    if (item.type === 'file') {
      this.$emit('handle-file-event', any_arguments_here);
      // alternatively, you can call this.performAction(item)
    }

    // you could also use a switch statement here
  }

}

<a href="#" @click.prevent="processAction(item)"
  <i class="[ 'fas fa-lg', icons[item.type] ] "></i>
</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

The Vue warning message indicates that the prop "scrollThreshold" did not pass the type check. The expected type was Number, but a String was provided instead

Every time I open my App.vue toolbar, I encounter this error. [Vue warn]: Invalid prop: type check failed for prop "scrollThreshold". Expected Number, got String. <v-toolbar dark color="pink darken-4" class="toolbar" flat fixed ...

Learn the process of passing Laravel route parameters to Vue components

As a newcomer to Vue, I've spent a lot of time searching on Google but haven't been able to find a solution that fits my current situation. I'm not sure how to pass a route into a Vue component. Is there a way to do this in Laravel, specific ...

Utilizing Vue.js to track and navigate through browsing history using the browser's

I'm currently working on an application using Vue and Laravel. Instead of relying on vue-router, Laravel is managing my routes. Within my parent component, I am dynamically loading components based on the state of an object in the data. One of the m ...

Going through items in a container

Is it possible to pass X number of components into a slot and iterate through them in Vue? Here's an example... <Foo> <template #abc> <Bar /> <Bar /> <Bar /> </template> <template #def>Baz</tem ...

Displaying or concealing an input field in vue.js depending on the selection of a radio button

I am currently working on customizing a pre-built form in Vue.js, where certain inputs are displayed or hidden based on the selection of two radio buttons: <b-form-group label-class="ssrv-form-control"> <div class="ssrv-5"& ...

Establishing the State Within the useEffect Hook

I am struggling to update my state with an array of objects in my code. It successfully populates an empty form with fetched data, but setting the state to that data is not working. Below is the snippet of my code: const [postMItems, setPostMItems] = useS ...

Amplify fails to detect existing Vue.js project when using Amplify

I have taken over a Vue.js app with AWS Amplify that was previously developed by another team. They utilized the Amplify Cli to integrate Auth into the application. After pulling down the project from GitHub, I noticed that the Auth service is functioning ...

Creating an IntersectionObserver with the Composition API: A Step-by-Step Guide

I am currently in the process of incorporating an IntersectionOberver that will update the url once the viewport transitions into a new section. I came across This thread and now endeavoring to apply it in vue 3 compositon api. The script is being integra ...

How can you set the Quill text editor to read-only mode in Vue after clicking a button?

I have a quill text editor that I want to customize the default setting to be readonly. When a button is clicked, this setting should toggle between true and false. Here is my component code: <template> <div ref="editor"></div> ...

Using Middleware to Access LocaleStorage in Universal Mode

Here's the dilemma: My understanding is that accessing LocaleStorage from Middleware in Universal mode is currently not possible (at least not out-of-the-box.) Question: Is there any way to solve this issue? Are there any modules or solutio ...

The requested module components/Home could not be located by NativeScript

Upon completion of generating a Vue NativeScript app and launching it with the following command: tns preview An error is displayed: *** Terminating app due to uncaught exception 'NativeScript encountered a fatal error: Error: Could not find module ...

"Utilizing the Datatable feature in Vuetify for selecting multiple rows with the Shift+Click

I'm currently using Datatable by Vuetify version 1.5.x I have set up the checkboxes to allow for multiple row selections, and I'd like to implement a Shift + Click functionality similar to how it works in Gmail, so users can select multiple rows ...

What is the importance of using getters for functions involving Moment.js in vueJS and typescript?

weekOfMonth() calculates the current month and week within that month. <template> <h3>{{ weekOfMonth }}</h3> </template> <script lang="ts"> export default class HomeView extends Vue { const moment = require(& ...

Bring JavaScript Function into Vue's index.html File

Recently in my code files, I noticed the following: function example() { console.log("testing"); } In another file, I have something like this: <head> <script src="../src/example.js" type="text/babel"></sc ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

Uploading files with Vue.js bindings

Encountering an issue while attempting to upload a file using the Vue Upload Component, particularly with binding variables for selection. The specific component being utilized is available at https://github.com/lian-yue/vue-upload-component. I have foll ...

Struggling to create an expandable v-data-table using Vuetify 3?

I've been working on creating an expandable v-data-table in Vue3 and Vuetify3. The regular data table was functioning properly, but when attempting to implement an expandable v-data-table, it doesn't show anything on display besides loading data ...

Vue Error: Unable to access 'this' as it is undefined

Why is this undefined in this context? When I click on logout, the browser console shows this error: TypeError: this is undefined <script lang="ts"> import Vue from "vue"; import { getModule } from "vuex-module-decorators"; import Component from " ...

How do I use Vue.js to capture keypress events and update the input value in real-time?

Here is the scenario I am facing: https://codepen.io/anon/pen/WYJopq I have implemented a functionality to track key presses and duplicate the input into another field with the following code snippet: [![methods: { clone: function() { this.m ...