What is the recommended way to include an image in a v-for loop in Vue.js?

I have attempted various online solutions, but I am still unable to display images on the screen. Could it be a simple mistake? The file names and folders are accurate.

When providing the path, I aim to retrieve the image associated with the sub-club name by dynamically selecting it from the folder. For example, Art.jpg. Your assistance would be greatly appreciated.

<template>
    <div>
        <div class="container">
            <a class="logo" href="#">Social Interest e-Club</a>
            <div class="start">Start</div>
            <div class="progress-bar-front bar"></div>
            <div class="progress-bar-back"></div>
            <div class="finish">Finish</div>
        </div>

    <form class="questionnaire-result" action="#">
        <h1 class="h1">Here are your result!</h1>
        <div class="grid-container">
            <h2 class="sub-club"> Sub-Club</h2>
            <h2 class="score"> Score</h2>
            <h2 class="join-que"> Want to Join?</h2>
            <div class="sub-club-section " v-for="(subclub,index) in subclubs" :key="index">

                    <img class="image" :src="'@/assets/sub-clubs-images/'+ 'subclub.subclubName'+'.jpg'" width="75">
                    <h3 v-if="subclub.score>50" class="score-result" style="color:#0cf12a ">{{subclub.score}}%</h3>
                    <h3 v-else class="score-result" style="color:red ">{{subclub.score}}%</h3>
                    <div v-if="subclub.score>50">
                        <input class="join-btn option-input checkbox" type="checkbox" v-model="subclubName" :value="index" >
                    </div>
                     
            </div>

        <button @click=" goToHomePage()" class="button "><span> JOIN </span></button>

        </div>
    </form>

    </div>
  
</template>

<script>
export default {
    name:"result",
    data(){
      
        return{
            subclubs:[
                { 
                      id:1,
                      subclubName:"Yoga",
                      score:70,
                
            },
            {  
                      id:3,
                      subclubName:"Novel",
                      score:60,
                   
            },
                {  
                      id:4,
                      subclubName:"Piano",
                      score:45,
           
            },
            
            ]
        }
    },
    methods:{
            goToHomePage(){
                this.$router.push("/");
            }

    }
}
</script>

Answer №1

To access the root (src) directory URL, simply using "@/assets/" will not suffice. You need to wrap the string with require() and eliminate the quotations from the subclub.subclubName variable. Here's how:

<img class="image" :src="require('@/assets/sub-clubs-images/' + subclub.subclubName + '.jpg')" width="75">
                

You can also utilize ES6 template literals for concatenating strings with variables like so:

<img class="image" :src="require(`@/assets/sub-clubs-images/${subclub.subclubName}.jpg`)" width="75">

Answer №2

To correctly utilize the image, it is essential to include the 'require' function in your code. Here's an example:

<img class="image" :src="require('@/assets/sub-clubs-images/'+ subclub.subclubName+'.jpg')" width="75">

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

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Tips for successfully utilizing hyphens when passing an object property as an argument

Does anyone know how to pass an object property with a hyphen in it as an argument? I'm having trouble with this issue. Object { "section-id": 1, ... } HTML <div *ngFor="let section of sections" (trackScrollLeave)="leave(section.sectio ...

Setting up Content Security Policy (CSP) with inline styles in your Vue or Nuxt application:

I am facing an issue while trying to deploy a Nuxt application due to a problem with Csp. I have included all the Sha256 values in my Csp, but there are still some lines causing trouble. It seems like the lines including :style="". What could be the potent ...

The output from the Python and SQLite combination is accurate, however the HTML rendering is not displaying the data correctly

Retrieving data from a database using different methods can yield varied results. When the method is set to 'get', it returns all information, but when it's 'post', it only returns the searched item. Although the post method return ...

Differences between Javascript object constructor and object literal

Similar Questions: Creating Objects - New Object or Object Literal Notation? Literal Notation VS. Constructor to Create Objects in JavaScript As I embark on my initial Javascript tutorial journey, I have come across two distinct methods of creatin ...

Selecting a JSON object at random

My data is stored in JSON format. [ ["Apple","A"], ["Orange","O"], ["Grape","G"], ["Kiwi","K"] ] Is there a way to randomly select an array item from this data (e.g. ["Grape","G"])? var letterNum = ""; $.ajax ( { url:"getletter.json" }).done( ...

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

Eradicate HTML by assigning empty values to certain attributes

Allowing the user to copy the HTML code of a div by clicking a button. Some attributes, such as for videos: <video loop muted autoplay> may appear like this after copying: <video loop="" muted="" autoplay=""> The ...

Tips for incorporating Bootstrap classes into a React project, setting the className attribute to an empty string

After setting up Bootstrap and Create-React-App using npm on my local machine, I proceeded to create a new React app. The first component I worked on was counter.jsx: import React, { Component } from 'react'; class Counter extends Component { ...

Fixing the Timeout Error in Node.js & Mongoose: A Step-by-Step Guide

After developing an API, I encountered the following issue: const express = require("express"); const router = express.Router(); const {getAttendanceSheet,getDailyAttendance} = require("../../services/attendanceService"); router.get(& ...

Unable to retrieve the desired dropdown element using xpath location strategy

On my website, I have a drop-down menu for selecting time zones and I need to be able to access the options easily. https://i.sstatic.net/jR4gx.png Here is the HTML code snippet: <li> <div id="ember2503" class= ...

Exploring the components of the scene with three.js

I have a desire to explore each element within a particular scene. These elements come in various forms such as THREE.Object3D, THREE.Mesh, and more. Some of these elements contain a property called children, which is essentially an array of other elements ...

Uncover the HTML tag associated with specific text on a webpage with the help of selenium

<div class="searchSummary floatL"> <span>18</span> results for "gloves" </div> Can someone assist me in using Selenium to extract the 'span' tag containing '18'? I am trying to specifically retrieve the 'sp ...

Display a dropdown list using ng-repeat to prevent selecting the same value multiple times

Within my ng-repeat loop, I have a drop-down menu and an add button that allows users to add new drop-down menus to the list. However, I am looking for a way to restrict the second drop-down menu from selecting the same value as the first one. In other wor ...

Error: The jasmine framework is unable to locate the window object

Currently, I am testing a method that includes locking the orientation of the screen as one of its functionalities. However, when using Jasmine, I encountered an error at the following line: (<any>window).screen.orientation.lock('portrait&apos ...

An issue occurred when retrieving the input value during a (change) event within a nested *ngFor loop in Angular

Within my table, I have implemented a nested loop using the *ngFor directive: <tbody> <tr *ngFor="let dept of salesTarget; let i = index"> <td>{{dept.dept}}</td> <td *ngFor="let month of monthList; ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

All outcomes being displayed from Youtube's json feed

Currently, I am retrieving a youtube playlist by using the following link: I'm curious if there is a method to display all 250 videos from my feed instead of just the 25 that are currently being shown. Any assistance on this matter would be highly a ...

The ng-repeat-start feature is not functioning properly across different levels

I am attempting to utilize the ng-repeat-start directive in order to construct a table that resembles the following: https://i.sstatic.net/Qgc91.png The structure of my JSON data is as follows: [ { "name": "Chapter 1", "parts": [ { ...

Exploring the capabilities of chromaprint.js within a web browser

I'm currently in the process of developing a music streaming platform and I'm looking to include the chromaprint.js library for deduplication purposes. In my workflow, I utilize browserify and gulp. Despite the fact that the library claims it ca ...