How come require() doesn't resolve the image path when passed as a prop in NuxtJS?

I am encountering an issue in my NuxtJS project where a component is not displaying an image correctly. Despite passing the image path directly to :src="imageAddress", it does not resolve nor throw an error. I attempted using the path inside require() to properly resolve it, but now I am faced with a Nuxt error: "Cannot find module '~/assets/icons/crown.png'". Strangely, when I placed an img element directly in index.vue, it displayed fine. Any insights on why this might be happening? Here's how my code is structured:

pages/index.vue
<template>
  <ChildComponent image-address="~/assets/icons/crown.png" />
</template>

___________________________________________________________________

components/ChildComponent.vue
<template>
  <img v-if="imageAddress.length" :src="require(imageAddress)">
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    imageAddress: {
      type: String,
      required: true,
      default: ''
    }
  }
}
</script>

Answer №1

If you want to customize the method in ChildComponent, you can create a new function like this:

generateUrl (img)  {
  return require(`~/assets/icons/${img}.png`);
}

Then, in your template, use it like this:

<img :src="generateUrl(imagePath)" alt="" />

Answer №2

Sharing my solution that worked for me. I encountered an undefined error when using require, so I switched to using import instead.

import iconImage from '~/asset/icons/crown.png';
<template>
  <ChildComponent :icon-image="iconImage" />
</template>

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

Exploring Vue 3: Crafting a custom plugin using the composition API and enhancing it with Typescript type augmentation

Encountering an issue with displaying plugins properly within <script> and <template> tags on WebStorm. Firstly, let's take a look at my files and configuration: tsconfig.config.json { "extends": "@vue/tsconfig/tsconfig. ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

"Unpredictable test failures plaguing my Node.js application with jest and supertest

Recently, I've been working on developing a REST API that accepts a movie title in a POST request to the /movies route. The API then fetches information about that movie from an external API and stores it in a database. Additionally, when you make a P ...

Should I utilize capacitor's geolocation or opt for capacitor-community's background-location?

Currently developing a mobile app using Ionic/Vue 6 that traces the path of hikers. I have reached the stage where GPS information is required, and the challenge is making sure the GPS plugin remains active even when the user keeps their phone in their p ...

Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32']; $('.grooveTable&apo ...

Express: issue retrieving numbers from request body array

JavaScript / TypeScript Issue: export const updateSettings = catchErrors(async (req, res) => { console.log("updateSettings req.body: ", req.body) const { organizationId, formdata, updatedItems, updateQuota } = req.body; console.lo ...

Vue.js: In a third-party library, the reference to "this" is coming back as "undefined"

My third-party script contains code in the following format ( function initialMethod(scope, factory) { // 'scope' is undefined when used in Vue // but it works fine in React and Angular } (this, function function1(param1) { ...

Destructuring array in React using Javascript

I'm currently exploring ReactJS and I'm facing a dilemma in understanding the destructuring process in the code snippet below: const IngredientsList = ({ list }) => React.createElement('ul', null, list.map((ingredient, i ...

Obtain an Element Using Puppeteer

Currently grappling with a sensitive issue concerning puppeteer. The HTML structure in question is as follows: <tbody> <tr rel="0" class="disabled" id="user6335934" class="odd"> ...

Executing Code Within Promises and Utilizing return Statements

When using promises, do I need to explicitly return the resolve and reject methods? The code runs smoothly for single condition statements, but what happens if there are multiple conditions - will reject and resolve automatically end or do we need to use ...

[VUE Alert]: Rendering Error - "Sorry, there is a type error: object is currently undefined."

<script> const app = new Vue({ el: '#app', data:{ results:{} }, mounted() { axios.get('{{ route('request.data') }}').th ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

What could be causing the issue preventing me from updating my SQL database through AJAX?

$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'functions/delivered.php', data = {'action': clickBtnValue}; $.post(ajaxurl, da ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

Button for AngularJS delete request

I have developed a live polling application that allows users to create, view, and delete questions from the table pools stored in the RethinkDB database. The issue lies with the delete functionality. While sending a DELETE request using POSTMAN successfu ...

In Visual Studio 2022, curly braces are now positioned on the same line for JavaScript code

I'm struggling with keeping Visual Studio from moving my curly braces to a new line whenever I auto format the code. Here's an example: Let's say I write this code: $('#details-modal').on('change', '#Foo1', fun ...

Gaining entry to a JSON object within an array

I've completed various courses on JSON and put in a lot of effort to troubleshoot this bug. However, it seems that my question is too specific and I require a practical example. JSON { "date": "2017-10-15", "league": "NHL", "odds": "spreads", ...

Tips for Serializing and Deserializing an XML Document using Javascript

I keep encountering the error 'parameter1 is not a valid node' when using document.adoptNode. Here's the code snippet in question: $.ajax({ type: "GET", url: url, datatype: "xml", success: function (results) { ...

When the ENTER key is pressed, trigger a function within the form instead of submitting it

Incorporating a table with filterable data utilizing the jQuery DataTables library, I face an issue. The said table is situated within a form where selecting rows (via checkboxes in one column) prompts the SUBMIT button to add them to a collection. The ta ...