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

Ways to implement collapsible functionality into table rows

I have a table on my website and I want to initially display only 3 rows. When the user clicks on the 'more' button, I want the rest of the rows to be displayed. However, when I tried implementing this with code, I encountered rendering issues. I ...

Nuxt has the ability to display the object itself, however, it cannot render its

I am using a directus API to fetch data, which is returned in an array of objects. I can render the array or an object from it, but not when trying to access a property of the object <template> <div class="grid grid-cols-2 gap-6 mt-6&quo ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

Is there a way to adjust the quantity of items in the shopping cart without the need to reload the webpage?

Currently, I am working on a test project using React & Redux. The project involves implementing a basket feature where I receive an array of products structured like this: products: [ { name: "Product one", count: 1, ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

What are the steps to retrieve marker data from a MySQL database and showcase them dynamically on a Google Map using AJAX? Addressing time constraints

Utilizing a combination of JavaScript, Google Maps API, PHP, and MySQL, my app is designed to extract a list of markers from a MySQL database, export them to a myXML.xml file, and then load these markers onto the map each time it loads. <!DOCTYPE html& ...

Solving the CORS problem between Vue.js and Flask: Troubleshooting XMLHttpRequest Blockade

Description: Currently working on developing a web application utilizing Vue.js for the frontend and Flask for the backend. The initial phase involves creating a simple login page, but encountering CORS (Cross-Origin Resource Sharing) issues when making r ...

Vee-Validate: Are flags on the field value yielding undefined results? Explained with TypeScript

The documentation states that by using a flag on the value of a field, I should be able to obtain a boolean. For example: computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); } }, I am working ...

"Using a WMD Editor to show the content of the wmd-preview division and questions on how to save this content in a

I am currently in the process of integrating the WMD editor into my website. Everything seems to be functioning correctly so far, but I have hit a roadblock: How can I store the entered information in my database? I have developed a JS/Ajax function that a ...

Using jQuery's $.ajax() function to make an asynchronous request, and then passing the

I'm currently utilizing the jQuery $.ajax() function within a parent function that passes values into the ajax call. I am looking to have a custom callback function that can access the data parameter returned from the success function of the ajax call ...

Using the class attribute for Pagedown instead of the id keyword

I am utilizing Pagedown, which necessitates giving the id wmd-input to a textarea. This requirement is outlined in Markdown.Editor.js as follows: function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); ...

Creating a new version of an existing method found within a component in a Vue store.js file

As I navigate through the learning curve of vue.js, a seemingly simple question has arisen: how can I achieve the following task? Within one of my vue components, I am facing challenges with the implementation of the "loadSuggestedUsers" method. Here is t ...

AngularJS textbox failing to recognize line breaks as expected

I am struggling with the following HTML code: <div class="form-group"> <div class="input-group col-sm-12"> <label for="" class="control-label">Comments</label> ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

I wish to substitute a form field with a different one once the value of another field matches a specific condition

The issue I'm facing is that the field disappears once "US" is chosen and does not revert back to the options when another choice is made. teacher_signup.html {% block content %} <h2>Sign Up As Teacher</h2> <form method="post> ...

Is it possible to retrieve the parent object?

My code snippet is as follows, and I'm struggling to access the data object from within the innerFn function. Is there a way to accomplish this? export default { data: { a: "a", b: "b" }, fn: { innerFn: () => co ...

What is the best way to reorganize the switch case in order to invoke methods from a class?

I have a special character called Hero within my game, this Hero inherits characteristics from the Player class and can perform a variety of actions. The majority of these actions are customized to suit the Hero's abilities. class Hero extends Player ...

Converting JavaScript QML objects to C++ QT components

I have a QML JavaScript function that generates and returns a component called Item: function createComponent() { var component = Qt.createComponent('MyComponent.qml'); var obj = component.createObject(container, {'x': 0, &apos ...

Adding the Authorization header in an Ajax request within ExtJS can be easily done by including the

I've been struggling to upload a file using ExtJS and web API. The issue I'm facing is that when trying to send an authorization header to the server, it always returns as null. I even attempted to include the header in the XHR request within the ...

Tips for resolving a blank screen issue when attempting to render components using the `:is="component"` attribute

Working with NativeScript-Vue for Android, my goal is to display a component based on button taps. To achieve this, I am utilizing this plugin which helps in integrating a global SideDrawer for smooth navigation. The buttons within the SideDrawer are used ...