Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use

require('../assets/img/item-image.png')
. However, I'm uncertain how to handle it in this scenario.

Component:

<div v-for="(item, index) in items">
    <img :src="item.src">
</div>

<script>
    import axios from 'axios'

    export default {
        name: 'componentName',
        data () {
            return {
                items: null   
            }
        },
        mounted () {
            axios
            .get('./test.json')
            .then(response => (this.items = response.data))
        }
    }
</script> 

JSON file:

    [
        {
            "id": 1,
            "title": "item title",
            "src": "../assets/img/item-image.png",
            "alt": "item-image",
            "text": "item body"
        }
    ]

Answer №1

To ensure that your images are included when bundling with Webpack, it is important to continue using the require() function.

Since Webpack bundles during compile time while image paths are only known at runtime, a good practice is to keep a part of the path static so that Webpack can accurately include the necessary files.

For instance, if all your images reside under ../assets/img, a recommended approach would be:

async mounted () {
  const pathRegex = /^\.\.\/assets\/img\//
  const { data } = await axios.get("./test.json")
  this.items = data.map(item => ({
    ...item,
    src: require(`../assets/img/${item.src.replace(pathRegex, "")}`)
  }))
}

By following this method, Webpack will bundle all files located under ../assets/img and successfully resolve the paths provided at runtime.

More information can be found at https://webpack.js.org/guides/dependency-management/#require-with-expression

Answer №2

Make sure to include the require statement in your code.

<img :src="require(item.src)">

Answer №3

After facing an error with the regex for adding require to the src attribute in the json, I decided to try a different approach that ended up solving the issue.

In this scenario, I am using fetch() to retrieve the json data from a server being monitored by json-server. The json is structured as an array (cokeImages) of objects which can be converted using res.json().

{
  "cokeImages": [
            { 
                "title": "Cocacola Life", 
                "description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
                "src": "../assets/cocacola-cans/cocacola-life.png", 
                "id": 1, 
                "name": "cocacola-life",
                "nutrition": [
                    { "title": "sodium", "value": "150 cl", "percent": "25%" },
                    { "title": "Total Fats", "value": "0g", "percent" : "0%" },
                    { "title": "sodium (mg)", "value": "40mg", "percent": "0%"},
                    { "title": "potasium", "value": "4g", "percent": "0%" },
                    { "title": "calcium", "value": "0g", "percent": "0%"}
                ]
            },
            { 
                "title": "Cocacola Zero", 
                "description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
                "src": "../assets/cocacola-cans/cocacola-zero.png", 
                "id": 2, 
                "name": "cocacola-zero",
               ... (and so on)...


A crucial observation was that the name property in each object matched the name used in the images' src. Utilizing this information, I employed the map() method to incorporate require into each src attribute.

mounted(){
      fetch("http://localhost:3000/cokeImages")
      .then(response => response.json())
      .then(arrayOfOjects => {
        console.log(arrayOfObjects)
        this.cokeImages = data.map(eachObject => {
          return {...eachObject, src: require(`../assets/cocacola-cans/${eachObject.name}.png`)}
        })
        console.log(this.cokeImages)
      })
      .catch(err => {
        console.log(err.message)
      })
    }

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

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

What is the best way to showcase information retrieved using the getDocs function from Firebase Firestore?

Hello! I am currently exploring the world of Firestore and facing a challenge. My goal is to retrieve a data object from Firestore, set it as state, and then display it on my application: Below are the imports that I have utilized for this task (please ig ...

Converting JSON data to a different JSON format through JOLT Transformation

I am a newcomer to JOLT and finding myself stuck with this specific requirement. I have looked at some examples online, but none seem to fit my unique structure needs. Hopefully, someone will be able to understand what I am trying to convey. Input JSON [ ...

What is the best way to securely store data in a Vue single-page application?

Let's say I have some confidential information that I want to hide in my Vue app, such as the following string: This is top secret! I've placed this content in my LoggedInHome.vue Component. This Component is only accessible when a User is logg ...

Set restrictions on the element with a fixed position

My div has a position: fixed that scrolls correctly, but I want it to stop when it reaches specific y-axis boundaries. How can I achieve this without flickering and maintaining performance? The behavior of Twitter's right panel is similar to what I&ap ...

Browser crashing due to drag-and-drop upload of desktop images

I've set up a form for uploading images using ajaxForm. I added a feature where users can drag and drop photos from their desktop (HTML5 drag & drop). Everything works smoothly when the photo is small, around 2mb. However, an issue arises when attempt ...

Transform JSON key utilizing jmespath technique

What benefits are there to converting or modifying JSON keys using jmespath? For instance, suppose I have a JSON structure like this: [ {"topic_id": 123, "name": "Topic 1"}, {"topic_id": 234, "name": "Topic 2"} ] How can I change the key "topic_id" to j ...

Challenges with Access Permissions on Amazon S3 Hosted Static Website

After successfully configuring Cognito-based authentication and testing it on my local machine, I encountered an error when deploying the compiled Nuxt application to S3. The error message received after login is: <Code>AccessDenied</Code> < ...

What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link. var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.37859 ...

Connect an input in VueJS to a VueX store state value

As someone new to VueJS, I'm currently working on a VueJS application that provides information about a Github user. For example, you can check out details for . I've set up a store using VueX, but I'm facing an issue with updating the valu ...

After developing a React application to fetch data from my own API, I encountered the following error message: "TypeError: video.map is not a function". See the code snippet below:

import React, {useEffect, useState} from "react"; import Axios from "axios"; const VideoPage = () => { const [video, setVideo] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchVideoData = async() =&g ...

Displaying JSON data within a div section using Ajax and jQuery is not possible

I have generated a JSON in a specific format from an external PHP file: [ { "title": "Welcome!", "description": "The world has changed dramatically..", "image": "img/strawberry-wallpaper.jpg" } ] I am trying to use this data to populate a par ...

I am having trouble identifying the error in the code below

Let's consider a scenario where we have a case class named Student that includes the attributes firstName and lastName. case class Student(firstName: String, lastName: String) In order to work with JSON data representing a sequence of students, we n ...

Checking form data validity before submission in JavaScript and PHP

My goal is to send data to a PHP script using the POST method. I need to ensure that the form input is valid before initiating an AJAX request. $('#submitccform').click(function() { function validate() { var valid = true; var messa ...

How can I detect when an image is loaded in a specific container division using jQuery?

I have a container with multiple images inside, and I would like to capture an event each time an image finishes loading. For example: <div id="container"> <img src="..." /> <img src="..." /> <img src="..." /> ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

Unable to access property 'scrollToBottom' as it is undefined

I'm encountering the error "Cannot read property 'scrollToBottom' of undefined" and haven't been able to find a solution anywhere, hence this post: Here is my use case: I have a custom accordion list, and on click of one of the list i ...

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

Error message: "Encountered a MalformedURLException when attempting to use the $ref keyword in a

When working with a json schema that references another json schema located in a different folder using "$ref" (relative path), I encounter a "MalformedURLException". { "$schema": "http://json-schema.org/draft-07/schema#", "$ref": "#/definitions/Base" ...

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...