Issue with binding an image from an object to an img src in Vue.js

I am currently attempting to dynamically bind an object's URL to my component, but I am facing some issues. It seems to only work when using 'require' or linking it directly like this:

"v-bind:imagem="/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png""
, or by using relative paths such as '../imgs/anuncio.png' or '@/imgs/anuncio.png'.

<template>
   <div>
      <site-template>
         <div class="anuncio">
            <anuncio v-for="anuncio in anuncios" v-bind:key="anuncio.id" v-bind:imagem="anuncio.imagem">

            </anuncio>
         </div>

      </site-template>
   </div>
</template>

<script>
import SiteTemplate from '@/templates/SiteTemplate'
import Anuncio from '@/components/anuncio/Anuncio'

export default {
    name: 'Home',
    components: {
       SiteTemplate,
       Anuncio
    },
    data () {
       return {
          anuncios: [
             { "id": 1, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 2, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 3, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 4, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 5, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" }
          ]
       }
    }
 }
 </script>

Below is the code for my "Anuncio" component:

<template>
    <div class="anuncio">
        <div class="w3">                
          <img class="img" v-bind:src="imagem"/>
       </div>
    </div>
</template>

<script>
export default {
    name: 'Anuncio',
    props: ['titulo', 'imagem'],
    data () {
        return {
        }
    }
}

</script>

Answer №1

Here is the solution you've been looking for:

To display images in your Anuncio component, you need to specify the path within the require() method. Your img HTML tag should be something like this:

<img class="img" v-bind:src="require(`../imgs/${imagem}`)"/>

In the array containing image paths, provide only the names and add .png extension as shown below:

anuncios: [
             { "id": 1, "imagem": "anuncio.png" },
             { "id": 2, "imagem": "anuncio.png" },
             { "id": 3, "imagem": "anuncio.png" },
             { "id": 4, "imagem": "anuncio.png" },
             { "id": 5, "imagem": "anuncio.png" }
          ]

Give it a try!

Answer №2

After setting up your project with vue-cli (https://cli.vuejs.org/), you should see an assets directory in the /src folder.

Simply move your images folder into the assets directory and update the image path to @/assets/imgs/anuncio.png (no need for require()).

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

Displaying the contents of a local HTML file in a div

I am attempting to load a local HTML file into a div, however it is not displaying any content on the page despite showing an alert. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> ...

Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props: text = the text to display in the link. icon = the identifier of the icon to display next to the link. < sidebar-link text="Home" icon="fa-home"> Below is the .Vue ...

How can you execute PHP code within another PHP script without triggering a redirect?

I'm faced with a situation where I have two php files, namely abc.php and def.php. My goal is to only display abc.php in the browser URL bar when it executes. Additionally, upon clicking the submit button on my HTML page, abc.php should be triggered t ...

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

Unable to display and conceal div elements

<ol class="novice"> <li> <p class="glava">HTML</p> <div class="vsebina"> <p>Hyper Text Markup Language (slovensko jezik za označevanje nadbesedila...</p> </div> </li> <li> ...

Using AJAX to send an ID to another HTML page allows for the creation of a unique WHERE clause

UPDATED: MAY 17, 2017 9:50 AM I am currently working on two HTML pages that both utilize AJAX to fetch data upon page load. I now have a requirement where I need to pass an ID from one HTML page to another in order to retrieve specific data using a WHERE ...

Tackling JavaScript: Exploring Ternary Short Circuit and If Short Circuit

I am attempting to optimize the code by using a ternary operator to quickly return false. My understanding was that using a ternary in this scenario would have the same outcome as the if statement below it, which is to instantly return false if the lengths ...

A guide to successfully interacting with multiple elements simultaneously at a single spot

Within my graphic chart, I have various dots that may be located in the same spot. I am looking for a way to handle clicks on two or more elements simultaneously in Vue 3. Do you know of any straightforward methods to achieve this? I attempted using refs ...

What is the reason for not modifying the filtered and sorted data?

I am currently working on implementing filter options for an item list, but I am facing an issue where the filtering does not work when selecting dropdown options. Array in App.jsx const cameraShowList=[ {id:1,model:"Canon",title:"Canon ...

Creating a peaceful web platform with React that supports several user roles

I am in the process of developing a single-page web application that must be completely restful, which is new territory for me. One challenge I'm facing is determining how to efficiently render the user interface for different roles using React. With ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...

Adjusting the height of the v-footer

I'm having trouble adjusting the height of the v-footer component. According to the documentation, I should be able to use the height prop, but when I try height="100px" or height="50%", the footer doesn't change. What could be causing this issue ...

What are the best ways to simulate dependencies for testing in node.js?

Is there a way to "mock" dependencies used with require('dependencyname') in order to write unit tests for my application? ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

The "ID" value for the row that was chosen is unable to be parsed with AJAX JQUERY

After populating an HTML table with data retrieved from a database using PHP, I encountered an issue while trying to fetch the correct ID using AJAX. Following a recommendation to use classes to build my jQuery code, I find myself stuck and unsure of what ...

"Enhance Your Smart Contract Interaction with Algrand's Method Calling

Currently, I am working on integrating an Algorand smart contract with a Next.js application. To sign transactions, I am utilizing Pera wallet. However, I have encountered an issue when attempting to call methods from the contract on the front end using th ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Why is it that this code can upload photos successfully, but not text files?

This is my PHP file for handling form actions. I have successfully implemented image uploads, but I am encountering an 'Invalid File Error' when trying to upload text files. What could be causing this error and how can I resolve it? <?php e ...

What is the best way to emphasize a table column when a cell is selected?

I successfully implemented a feature where a cell (td-element) is highlighted when clicked by the user. However, I now want the entire column to be highlighted with the cell itself having a slight variation. I am struggling with achieving the last part ...

What is the best way to convert Arabic language HTML into a PDF document on the client side?

Utilizing jsPDF and vue js, I successfully implemented a feature to export PDFs. However, I encountered an issue with Arabic characters not displaying properly. Can anyone provide assistance in resolving this problem? ...