What is the method for retrieving an image source using JavaScript?

I'm trying to retrieve the image source from my utils file and bind it to an img tag in my About.vue JS file, but I'm facing issues with the implementation. The first file is About.vue, and the second one is my utils file.

<template>
  <div>
    <Header></Header>
    <main>
      <section v-if="this.showAlert">
        <b-alert show variant="success">
          <h4 class="alert-heading">Well done!</h4>
          <p>
            This web-app was made by Gabriel Nunes, he did it all by himself.
            All these buttons and headers that you saw on the app, was made by
            him too.
          </p>
          <hr />
          <p class="mb-0">
            If you need anything from him, please contact via social networks.
            Social networks:
            <img
              :src="this.showImg.facebook.src"
              :width="this.showImg.facebook.width"
              :height="this.showImg.facebook.height"
            />
          </p>
          <p class="mb-1">
            <img
              :src="this.showImg.github.src"
              :width="this.showImg.github.width"
              :height="this.showImg.github.height"
            />
          </p>
        </b-alert>
      </section>

      <section v-if="!this.showAlert">
        <b-alert show variant="secondary">
          <h4 class="alert-heading">Well done!</h4>
          <p>
            Aww yeah, you successfully read this important alert message. This
            example text is going to run a bit longer so that you can see how
            spacing within an alert works with this kind of content.
          </p>
          <hr />
          <p class="mb-0">
            Whenever you need to, be sure to use margin utilities to keep things
            nice and tidy.
          </p>
        </b-alert>
      </section>
    </main>
  </div>
</template>

<script>
import Header from "./Header.vue";
import { pathImgObj } from "../../utils.js";
export default {
  components: {
    Header,
  },
  data() {
    return {
      showImg: {},
      showAlert: Boolean,
    };
  },
  created() {
    this.showAlert = confirm("Are you sure about this?");
    this.showImg = { ...pathImgObj };
  },
  methods: {},
};
</script>

<style>
</style>

Utils file js

export const config = {
  home: 'Home',
  anime: 'Animes',
  faq: 'FAQs',
  about: 'About'
}
export const pathImgObj = {
  facebook: {
    src: `./assets/img/facebook.png`,
    width: '30px',
    height: '30px'
  },
  github: {
    src: `./assets/img/github.png`,
    height: '30px',
    width: '30px'
  }
}

I am expecting to fetch the src, width, and height values from the utils file and pass them to my About.vue component. How should I proceed?

My current result shows no image being displayed. https://i.sstatic.net/fCDis.png

Answer №1

When Webpack processes a URL that is either required or imported, it determines the appropriate action to take. Specifically for image URLs, Webpack locates the image, performs any necessary transformations (such as scaling and optimization), stores the result in an output directory, and provides the resulting URL (e.g., dist/img/foo.abcd123.jpg).

vue-loader specifically handles static URLs when requiring <img>.src:

<img src="@/assets/foo.jpg"> ✅

<img :src="'@/assets/' + imgUrl1"> ❌
<img :src="imgUrl2"> ❌
export default {
  data() {
    return {
      imgUrl1: 'foo.jpg',
      imgUrl2: '@/assets/foo.jpg',
    }
  }
}

If dynamically binding <img>.src, manual requiring using the binding value or within the <script> block is necessary:

<img :src="require('@/assets/' + imgUrl1)"> ✅
<img :src="require(imgUrl2)"> ✅
<img :src="imgUrl3"> ✅
export default {
  data() {
    return {
      imgUrl1: 'foo.jpg',
      imgUrl2: '@/assets/foo.jpg',
      imgUrl3: require('@/assets/foo.jpg'),
    }
  }
}

Considering that the URLs in the utils file are dynamically bound within the template, vue-loader doesn't automatically require them, treating them instead as static assets in the public/ folder. For instance, a static URL like ./assets/foo.jpg corresponds to public/assets/foo.jpg.

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

What steps should I take to enable this SimpleModal to load automatically?

Is there a way to have the SimpleModal script load when the page loads instead of having to click a button? Thank you for your help! < div id='basic-modal' > <a href='#' class='basic'>Demo</a> </div> ...

What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files. Below is a snippet of the JavaScri ...

Encountering a 404 error with Laravel InertiaJS Vue after deployment on Hostinger

After uploading my project to Hostinger, I encountered an issue where only the homepage of the website was showing. Other components were resulting in errors like: GET https://appname.com/shop/all 404 (Not Found) vendor-5ByMKR7B.js:3. To troubleshoot, I at ...

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

Utilizing NodeJS to initiate an http request and interact with a hyperlink

I am implementing website conversion testing and want to modify this code so that 10% of the http requests also click on a specific #link within the page. What additional code do I need to achieve this? var http = require('http'); http.createSer ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

Which language is better for refreshing web pages: PHP or Javascript?

May I seek your opinion on this matter? I have the ability to refresh my page using two different methods, but I am uncertain of any potential drawbacks. Can you advise me on which one I should utilize? Edit: Specifically, I am referring to the use of he ...

Retrieve information from the third section by utilizing ajax

My current setup involves: Having a form in form.php for inserting data, Displaying data in table format with pagination on display.php, and Using validation.js for validating form data along with the following function: $('#pagiCount a'). ...

What is the process for creating an Account SAS token for Azure Storage?

My goal is to have access to all containers and blobs in storage. The Account SAS token will be generated server-side within my Node.js code, and the client will obtain it by calling the API I created. While Azure Shell allows manual creation of a SAS toke ...

Displaying MySQL information on an EJS document including references to other tables

Check out the project on GitHub I am currently working on retrieving quiz answers from a MySQL database and displaying them in a form using EJS templating within a node.js/express application. However, I am facing challenges with correctly mapping answers ...

Creating a star-based rating feature through directive implementation

Can anyone help me figure out why my static star rating system using angularjs/ionic is not showing up on the screen? I've been struggling with it and would appreciate some guidance. service.html <ion-list> <ion-item ng-repeat="busine ...

Using Regular Expressions in Firebase Functions to achieve a 'Clean Path' when utilizing app.use() in Express.js

Objective: I want Express to return /register when the browser URL is http://localhost:5000/register. This seemingly simple goal is proving to be a challenge with Express. Let's start by looking at my firebase.json: firebase.json: "hosting": { ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

Use JavaScript to dynamically generate a drop-down select menu

Is there a way to automatically expand a select menu dropdown using JavaScript or jQuery when a button is clicked? I am facing this challenge because I have a text field that allows users to input custom fields dynamically into a select input. My goal is ...

Retrieve all items on the webpage using the pattern "_ followed by 10 random characters" through JavaScript

On my webpage, there is a table containing table rows in the following format: <tr id="_C15DKNWCSV">text</tr> I am attempting to scan the webpage and extract all table rows that have an id in the format: id="_(10 RANDOM CHARACTERS)" I want ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

Tips for aligning and emphasizing HTML content with audio stimuli

I am looking to add a unique feature where the text highlights as audio plays on a website. Similar to what we see on television, I would like the text to continue highlighting as the audio progresses. Could someone please provide me with guidance on how ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

The mat-datepicker appears in a unique location each time it is opened

I am facing an issue with my mat-datepicker appearing in the opposite place when clicked on one component. How can I resolve this? I have two different components with mat-datepicker, but they behave differently. I suspect that imitating a click in one com ...

Tips for saving an image link when displaying an image in VueJS using the 'require' method

I am currently working on a project that involves displaying Pizza items with their respective images. Each Pizza object is stored in the database along with an imgUrl field. Strangely, the images are not showing up on the page, although I can see the alt ...