Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image:

<template>
    <div>
        <img :src="image" />
    </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    image: String
  }
}
</script>

Even though I try to bind an image path like this:

<MyComponent
    image="./assets/image-test.png">
</MyComponent>

The image does not display.

What steps have I taken so far?

I attempted to modify the code within the component to directly reference the image. In doing so, the image actually displayed:

<img src="@/assets/image-test.png" />

(Only with the @ symbol)

I experimented by changing the bound path in the component to:

image="@/assets/image-test.png">

However, this change had no effect on the outcome.

After finding this answer, I tried implementing the following:

<div>
    <img :src="getImage(image)" />
</div>

  methods: {
    getImage(path) {
      return require(path);
    }
  }

within the component. Unfortunately, this resulted in a runtime error:

Cannot find module './assets/image-test.png'

The complete stack trace of the error was:

runtime-core.esm-bundler.js?5c40:217 Uncaught Error: Cannot find module './assets/image-test.png'
    at webpackEmptyContext (eval at ./src/components sync recursive (app.js:1080), <anonymous>:2:10)
    at Proxy.getImage (MyApp.vue?059c:17)
    at Proxy.render (MyApp.vue?059c:3)
    at renderComponentRoot (runtime-core.esm-bundler.js?5c40:710)
    at componentEffect (runtime-core.esm-bundler.js?5c40:4193)
    at reactiveEffect (reactivity.esm-bundler.js?a1e9:42)
    at effect (reactivity.esm-bundler.js?a1e9:17)
    at setupRenderEffect (runtime-core.esm-bundler.js?5c40:4176)
    at mountComponent (runtime-core.esm-bundler.js?5c40:4134)
    at processComponent (runtime-core.esm-bundler.js?5c40:4094)

I even tried using the @ symbol in this approach.

If anyone could provide guidance on how to resolve this issue, I would greatly appreciate it. It seems there may be a specific way Vue handles images causing this problem, as mentioned in the linked post, but I am struggling to figure out how to correctly bind the image.

Answer №1

It is essential to have the image required in the parent component and defined in the script section for proper transpilation:

Parent

<template>
  <div id="app">
    <MyComponent :image="img" />
  </div>
</template>

<script>
import MyComponent from "./components/MyComponent.vue";

export default {
  name: "App",
  data: () => ({
    img: require("@/assets/logo.png"),
  }),
  components: { MyComponent },
};
</script>

MyComponent

<template>
  <div>
    <img :src="image" />
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  props: {
    image: String,
  },
};
</script>

If you use require in the template section, an error like the following will occur:

Error: /src/assets/logo.png hasn't been transpiled yet.

https://codesandbox.io/s/vueye-table-forked-vttj9?fontsize=14&hidenavigation=1&theme=dark

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

Step-by-step guide on uploading a local JSON file to Google Maps

I am in the process of creating a map for my website using the Google Maps JavaScript API. The map includes a local JSON layer that outlines a specific polygon area on the map. Everything worked perfectly when I tested it within Visual Studio, but when I t ...

When I open my website in a new tab using iOS and Chrome, the appearance of the absolute element is being altered

I am experiencing an issue with a div that is positioned absolutely at the bottom left of my website. When I open the site in a new tab using <a target="_blank" href="./index.html">, the bottom value is not being applied correctly ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

There seems to be a mysterious absence of chuck norris jokes in

I'm attempting to call two different APIs by clicking a button to display a random joke on the screen. I've created two separate functions to fetch the APIs and used Math.random() to generate a random number. If the number is greater than 50, one ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

What role does the sequence play in matrix transitions that involve rotating and translating simultaneously?

Attempting to animate a matrix3d with both rotation and translation concurrently has yielded unexpected results for me. It seems that changing the order of applying rotation and translation produces vastly different outcomes. http://jsfiddle.net/wetlip/2n ...

Disappearing Data: Struts2 Autocompleter's Entries Vanishing Upon Submit Button Click

I am currently utilizing the auto-complete feature from The issue I am facing is that when I type "Ball", the auto-complete suggests "Balloon". Even though both "Balloon" and "Balloon" appear in the text field and the list, when I click elsewhere on the s ...

Running multiple server and client codes on node.js simultaneously

I'm exploring the idea of establishing a network of nodes on my computer that have dual functionality as both clients and servers. Each node should be able to execute its unique server code and client code, allowing it to send requests to its individu ...

What is the correct way to declare a new variable for a JSON object?

Within my Node JS application, I have an endpoint where I am attempting to retrieve data from two separate mongo collections. However, when trying to combine this data, I am encountering difficulties adding a new property to the JSON object. const getLesso ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

Creating unique page styles using global styles in Next.js

I am facing a dilemma in my NextJS app. On the /home page, I need to hide the x and y overflow, while on the /books page, I want the user to be able to scroll freely. The issue is that Next only allows for one global stylesheet and using global CSS selec ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

The error message "ReferenceError: process is not defined" occurs when the 500 process is

Every time I try to import a library or use puppeteer, I keep encountering this problem and I'm not sure how to resolve it. My goal is to extract data from LinkedIn using https://www.npmjs.com/package/linkedin-client. Here's the simple code snipp ...

Looking to add elements to a specific div dynamically using jQuery? Let's explore how to insert comments seamlessly

I would like to implement a comment system that adds entered comments to a specific div. Here's the code I have so far: <ul class="comments"> <li> <a class="commenter_name" href="/">Dushyanth Lion</a> ...

When constructing a file directory URL, it is important to utilize the forward slash "/" in the filename

As I am creating a URL, the process involves taking the filename and using it to create a folder with that name. However, an issue arises if the name contains "/", as it causes the URL to break and creates an undesired location. For example: var fileDir ...

Knowing the appropriate time to divide a Vue component into multiple components (sub components)

When developing Vue components, what factors should be considered when deciding whether to break up a component into parent and child components or keep it as a single component with more functionality? I have integrated Vue into several areas of a non-SP ...

What is the best way to show the current date and time?

To filter out and display only the date from the array that is the largest compared to the current date, all dates are displayed. const states = States.select().exec() var curr = new Date(); for (var i = 0; i < states.length; i++) { var maxDate = ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

Instructions on setting div opacity when Overflow is set to visibleExplanation on setting opacity for div with Overflow

In my HTML code, I have a div element and an image tag stacked one on top of the other. The div is smaller than the image. I have set the overflow property to visible for the div. My query is, when I add an image to the image tag, the content that overflow ...

"Discover the steps to efficiently utilize the lookup feature with array objects in MongoDB

I am a beginner with MongoDB and I am trying to create a schema for my collection as shown below please note that all ObjectId values are placeholders and not real stockIn documents { serial:"stk0001", date:'2021-06-11', productInTra ...