Vue is having trouble loading dynamic src files, and the require function isn't functioning properly

I'm facing an issue with displaying a dynamic image. When I use the following code:

<img :src="src" alt="img">
It doesn't seem to work.

However, it works perfectly fine when I use:

<img src="../assets/img/banana.png" alt="img">

I have also attempted to use 'require', but I keep getting the error message:

Error: Cannot find module '../assets/img/banana.png'"

Answer №1

The issue lies in the absence of information regarding the module's location, which poses a challenge for webpack in resolving it.

Using a completely dynamic import statement like import(foo) is not feasible because foo could potentially point to any file or path within the system or project.

The import() function must include some level of detail about the module's location.

To address this, a BaseImage component can be created to replace dynamically sourced content starting with a specific path, in this scenario ../assets/, enabling webpack to pre-emptively understand this information.

For example:

<template>
  <img
    :src="computedSrc"
    :alt="alt"
    class="BaseImage"
    v-bind="$attrs"
    v-on="$listeners"
  />
</template>

<script>
export default {
  name: 'BaseImage',

  inheritAttrs: false,

  props: {
    src: {
      type: String,
      required: true,
    },

    /**
     * The alt tag is required for accessibility and SEO purposes.
     *
     * If it is a decorative image, which is purely there for design reasons,
     * consider moving it to CSS or using an empty alt tag.
     */
    alt: {
      type: String,
      required: true,
    },
  },

  computed: {
    // If the URL starts with ../assets/, it will be interpreted as a module request.
    isModuleRequest() {
      return this.src.startsWith('../assets/')
    },

    computedSrc() {
      // If it is a module request,
      // the exact module is not known on compile time,
      // so an expression is used in the request to create a context.
      return this.isModuleRequest
        ? require(`../assets/${this.src.replace('../assets/', '')}`)
        : this.src
    },
  },
}
</script>

Swap out img for the BaseImage component.

<BaseImage :src="img.src" :alt="img.alt"/>

Updated codesandbox link

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 is the best way to set a default function in a mongoose schema?

After spending quite a few hours trying to resolve this issue, I have finally turned to Stack Overflow for help. The problem I'm facing is with the promise pending errors on a specific field where I need to set a default value. Here's the code s ...

Node.js backend includes cookies in network response header that are not visible in the application's storage cookies tab

I am currently working on creating a simple cookie using express's res.cookie() function. However, I am facing an issue where the cookies are not being set correctly in the application tab. My project setup includes a React frontend and a Node backend ...

Issue with Typescript in react: JSX element lacks construct or call signatures

After upgrading TypeScript, I encountered the error mentioned above in one of my components. In that component's render method, I have the following code: render() { const Tag = props.link ? 'a' : 'div'; return ( < ...

Update the primary folder for the assets in the Vue build

Vue CLI 3.3 is what I'm using to develop projects for my vertical website with Vue. However, every time I build the project, the assets in dist/index.html always load from the root path. For example: <script src=js/chunk-vendors.b0f460c7.js>< ...

Is there a way to access a PHP value within a self-invoked jQuery function?

I have a page that creates n links using a foreach loop: ...some html and php code <?php foreach ($tables as $table):?> ... some elements generated ... <td><a onclick="setPortalId(<?php echo $table['id']?>);$('#file ...

What are some ways to maintain code efficiency when working with AJAX requests?

Looking at the code below, I am making two identical Ajax requests with only one line of difference. Is there a way to consolidate this into a function to maintain DRY (Don't Repeat Yourself) code? $('.searchable').multiSelect({ selecta ...

How can I display hardcoded array information as comments along with responses?

Currently, I am facing a challenge in displaying my hardcoded array data as comments with replies. The requirement is to achieve this within a single component file. While I have successfully managed to print the data out as a list, the desired outcome sh ...

Issue with pagination and filtering in Smart-table.js

Presently, my focus is on developing functionality for Smart-table.js, which requires the following features: Retrieve JSON data from a web service Create a table with pagination and filtering capabilities Implement filters for individual columns or globa ...

Steps to generate a fresh array from a given array of objects in JavaScript

Looking to transform an existing array into a new array of objects in Vue.js. Here's the initial array : import { ref } from 'vue'; const base_array = ref([ {id: 1, name: Pill, timing: [morning, noon, evening, night]}, {id: 2, name: Ta ...

Getting undefined while trying to iterate through data on a next js page using getStaticProps. What could be causing this issue?

Encountering difficulties while trying to output the page meta data in next.js when I execute: npm run build An error is thrown with the following message: Error occurred prerendering page "/blog/[...slug]". Read more: https://err.sh/next.js/pre ...

Ways to ensure text fits nicely within a container: HTML & CSS

Below is a code snippet: @import url('https://fonts.googleapis.com/css?family=Merriweather|Open+Sans'); .square { max-width: 460px; background: white; border-radius: 4px; box-shadow: 0px 5px 20px #D9DBDF; -webkit-transition: all 0. ...

Executing multiple click events using JavaScript

I have recently started learning JavaScript and am experimenting with the following script: <script type="text/javascript"> $(document).ready (function() { $('#apply').click(function() { $('#applyinfo').toggle ...

Step-by-step guide on how to make a POST request with session data to a specific endpoint in a Node.js server

Currently, I am utilizing express and have a task to execute a POST request to an internal endpoint in the server. Below is the code snippet I am using: request({ url : 'http://localhost:3000/api/oauth2/authorize', qs:{ transaction_id:re ...

Comprehending the Syntax of the ExtJS Framework

I have recently inherited a project utilizing Sencha's ExtJS framework without any handover or documentation. As I navigate through the code, I find myself trying to decipher certain syntax and exploring resources tailored for newcomers to this specif ...

Tips on extracting the image URL from a canvas element using Selenium in Java and leveraging JavascriptExecutor

My main objective is to extract the image URL from a canvas container. Here is what I have attempted: JavascriptExecutor jse = (JavascriptExecutor) driver; Object imageURL = jse.executeScript("arguments[0].toDataURL('image/png');", canvas); Un ...

"Implement a feature in v-data-table that allows the rows to be opened in a new tab using V

Currently, I am utilizing vuetify and looking to transform each row into an a tag that opens in a new tab automatically. This is how my table appears: <v-data-table :headers="headers" :items="campaigns" calcu ...

How can we determine which MenuItems to open onClick in a material-ui Appbar with multiple Menus in a React application?

While following the examples provided on the material UI site, I successfully created an AppBar with a menu that works well with one dropdown. However, upon attempting to add a second dropdown menu, I encountered an issue where clicking either icon resulte ...

I have a query regarding the load function and JSON

Is it feasible to achieve something similar to this? $.ajax({ url: "test.php", success: function(json, json1){ //I wonder if I can have more than one parameter here? $m0 = []; $m0.push(parseFloat(json)); alert($m0); //display 750 $m1 ...

Logging Modal Toggle Clicks

I'm looking for a way to track views on my media catalog page, similar to an Instagram page. Each piece of media is displayed in a modal, and I want to have a "view count" recorded every time a modal is opened for that media. Here is a basic example ...

Adjust Element Width Based on Scroll Position

I'm attempting to achieve a similar effect as seen here: (if it doesn't work in Chrome, try using IE). This is the progress I've made so far: http://jsfiddle.net/yuvalsab/op9sg2L2/ HTML <div class="transition_wrapper"> <div ...