Nuxt - Sending Relative Path as Prop Leads to Error 404

I am currently working with an array of JSON objects that I need to import onto a webpage. The process involves iterating through the data and passing the objects as a prop to a component. One of the attributes within the JSON data is a relative path for an image located in my /assets/ folder.

For example, the JSON structure:

[
    {
        "title":"val1",
        "img": "~/assets/image1.jpg",
        "text":"Lorem ipsum dolor sit amet"

    },
    {
        "title": "val2",
        "img": "~/assets/image2.jpg",
        "text":"Lorem ipsum dolor sit amet"

    },
    {
        "title": "val3",
        "img": "~/assets/image3.jpg",
        "text":"Lorem ipsum dolor sit amet"
 
    }
]

I am using a component from the Vue library (bootstrap-vue) that has an "img-src" directive for displaying images. However, when passing the prop with the image path to this directive, I am encountering a malformed path and a resulting 404 error.

Here is an example of usage:

<div>
    <b-card :img-src="data.img"></b-card>
</div>

<script>
export default {
    props: {
        data: {
            title: String,
            img: String,
            text: String
        }
    }
}
</script>

The requested URL for the image asset appears as http://localhost:3000/~/assets/image1.jpg. However, if I directly provide a static string path to the directive:

<div>
    <b-card img-src="~/assets/image1.jpg"></b-card>
</div>

The image loads correctly with the URL for the asset being http://localhost:3000/_nuxt/assets/image1.jpg

I am seeking assistance in understanding what might be causing this issue.

Answer №1

Fixing Props Declaration

It seems like there is an issue with how your props are declared. It's recommended to declare individual props for title, img, and text instead of using them within a single data prop. Here is the correct way to declare them:

export default {
    props: {
        title: String,
        img: String,
        text: String
    }
}

Handling Asset URLs in Nuxt

When working with asset URLs in Nuxt, it's important to note that vue-loader is used to load Vue Single File Components (SFCs) and automatically transforms asset URLs into Webpack module requests. For dynamic values like v-bind, you may need to explicitly use require. You can configure this behavior via the transformAssetUrls option in vue-loader.

The bootstrap-vue Nuxt plugin configures the transformAssetUrls to include <b-card>.imgSrc, allowing you to use

<b-card img-src="~/assets/image1.jpg">
without any additional handling.

If you have dynamic img-src URLs, you can resolve them using require, like this:

<template>
  <b-card :img-src="computedImg"></b-card>
</template>

<script>
export default {
  //...
  computed: {
    computedImg() {
      return require('~/assets/' + this.img.replace(/^~\/assets\//g, ''))
    }
  }
}
</script>

For a demo, you can check this 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

Is there a way to execute a PHP script using Ajax without needing any return values?

Currently, I am attempting to execute a php script with ajax without needing any output or echos. Is there a method to achieve this? Below is the approach I have taken: $('button')[1].click(function () { $.ajax({ met ...

Changing the color of a Navlink when focused

Can anyone help me modify the background color of a dropdown nav-link in Bootstrap? I am currently using the latest version and want to change it from blue to red when focused or clicked. I have included my navbar code below along with additional CSS, but ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

Ways to ensure your component is updated when there are changes to the props in N

I need to update the data every time there is a change in props within the component, and I want to display it without having to reload the page. pages/invoice/index.vue: <template> <div> <b-table-column field="InvoiceNo" ...

Switch out a new js file every time the page is reloaded

I have a JS file with various objects (var), and I'm looking to dynamically load a different object each time the page is loaded. For instance, upon page load, a new object 'temp' should be created with data from one of the objects in the JS ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

Preventing the addition of duplicate items to an array

My current challenge involves pushing containers into an array in my JavaScript code. However, once a container has been pushed, I want to prevent that same one from being pushed again. If you'd like to take a look at the JSfiddle where I'm work ...

streaming audio data from a MongoDB database to an HTML audio element

As part of my current project, I am delving into the realm of creating an audio player. The concept of database storage for files is relatively new to me, as my previous experience has mainly involved storing strings. Up to this point, here's what I ...

Starting the stored procedure/function using the sequelize.query() method

Below is the stored procedure I have written: CREATE OR REPLACE FUNCTION GetAllEmployee() RETURNS setof "Employees" AS $BODY$ BEGIN RETURN QUERY select * from "Employees"; END; $BODY$ LANGUAGE plpgsql; I am attempting to execute this stored procedure fro ...

Make sure to validate for null values when extracting data using the useSelector hook

Could someone help me with checking for null while destructuring data? const { vehicles: { data: { reminderVehicles }, }, } = useSelector((state) => state); The code snippet above is throwing an error message: Attempting to ...

Switch from Index.html to Index.html#section1

Currently, I am working on a website and sending someone a draft for review. However, the Home screen is designed as a 'a href' link with "#home". The issue arises when the website opens from my computer; it goes to ...../Index.html instead of .. ...

Animate the jQuery display property to show a table without changing any specified spatial dimensions

When utilizing jQuery's $.animate() on an element styled with display:table, any spatial dimensions that are not explicitly specified to change will animate. Check out the fiddle here In the scenario presented, the width is defined for animation, bu ...

Resolved the time zone problem that was affecting the retrieval of data from the AWS Redshift database in Next

Currently utilizing Next.js for fetching data from AWS Redshift. When running a query from DataGrip, the results display as follows: orderMonth | repeatC | newC 2024-02-01 | 81 | 122 2024-01-01 | 3189 | 4097 However, upon retrieving the same query ...

Enable lightbox functionality prior to all images being fully loaded

I have a large number of images (thumbnails) on my website and I am using the Featherlite lightbox plugin. However, when I click on one of the loaded images while they are still loading, the lightbox does not work as expected. Instead of opening in a modal ...

most effective method for establishing a relationship between a variable and its corresponding identification number

When retrieving results from a database with a simple PHP while loop, one of the data pieces includes a number that links to another table where the corresponding value is stored. While there are various ways to link this information and display the relate ...

Is it possible to bundle Live using Angular 2 and SystemJS-builder, even when attempting to load modules from node_modules?

I'm having a bit of trouble transitioning my angular 2 application into production. It seems to be searching for scripts within the node_modules directory. I'm fairly new to angular 2 and despite spending half a day looking for a solution, I can ...

Finding the equivalent of BigInt from Javascript in C#

After creating a JavaScript script that converts a string to BigInt, I encountered a challenge while trying to find a C# equivalent function. The original conversion in Javascript looked like this: BigInt("0x40000000061c924300441104148028c80861190a0ca4088 ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Tips for sending a parameter from a Vue component attribute to the component's SCSS

Recently, I have successfully created a tooltip component using pseudo-classes ::before and ::after. This component positions itself around an element based on the attributes assigned to it on various pages. For instance, here's an example of a toolti ...

Message displayed on picture carousel

<div class="slider"> <div> <img src="http://kenwheeler.github.io/slick/img/fonz1.png" /> <p class="projectname">Project</p> <p class="clientname">Client Name</p> </div> &l ...