When using VueJS to load an SVG file based on a variable within a for loop and utilizing v-html, the result returned is "[

I'm faced with a challenge of loading SVGs saved in separate files based on the content within a loop. Upon page load, what I see is:

https://i.sstatic.net/OiwyT.png

Hey there, check out my code snippet below:

<div
  v-for="(rec, index) in stats"
  :key="index"
>
    <div class="iconForeground align-self-center" v-html="require(`../../../assets/svg/dashboard/attributes/${rec.icon}.svg`)">
    </div>
</div>

Here's just a glimpse of the data function for brevity:

data() {
  return {
    stats: [{name: "Leadership", percent: "75", top: "5", icon: "leadership"}, 
            {name: "Innovation", percent: "25", icon: "genius-ideas"}] as Array<Record<string, string>>
  }
}

Any suggestions on how to achieve this?

EDIT Below is my vue.config.js setup:

const path = require("path");

module.exports = {
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: [
        "./src/styles/global.scss"
      ]
    },
    configureWebpack: {
      module: {
        rules: [{
          test: /\.svg$/,
          loader: 'vue-svg-loader'
        }]
      }
    }
  }
}

EDIT 2 Even after installing url-loader and following recommendations, image loading still remains an issue. Here's the updated vue.config.js:

const path = require("path");

module.exports = {
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: [
        "./src/styles/global.scss"
      ]
    },
    configureWebpack: {
      module: {
        rules: [
        {
          test: /\.svg$/,
          loader: 'vue-svg-loader'
        },
        {
          test: /\.(png|jpg|gif)$/i,
          use: [
            {
              loader: 'url-loader',
              options: {
                esModule: false,
              },
            },
          ],
        }]
      }
    }
  }
}

Lastly, here's a snippet from my HTML:

<div class="d-flex flex-column justify-content-center" :style="{marginRight: '24px'}">
    <div class="purpleDot"></div>
    <div class="iconForeground align-self-center">
       <img :src="require(`../../../assets/svg/dashboard/attributes/${rec.icon}.svg`)" />
    </div>
</div>

Answer №1

To solve this issue, you can implement dynamic components in your Vue.js application. Here is an example code snippet:

<template>
  div
    v-for="(m, i) in modules"
    :key="i">
    <component :is="m.image"></component>
  </div>
</template>

import PraiseIcon from "@/assets/svg/navigation-bar/Praise-Icon.svg";

components: {
  'Praise-Icon': PraiseIcon
},
data() {
  return {
    modules: [
        {
          name: "Praise",
          image: "Praise-Icon",
        }
      ] as Array<Record<string, string>>
  }
}

Answer №2

Get rid of the svg loader in your code

   {
          test: /\.svg$/,
          loader: 'vue-svg-loader'
        },

Include svg in your url-loader configuration

  test: /\.(png|jpg|gif|svg)$/i,
          use: [
            {
              loader: 'url-loader',
              options: {
                esModule: false,
              },
            },
          ],
        }

This issue is typically caused by your webpack loader settings

Try setting the esModule option in url-loader to false.

Implementing this change should resolve the problem.


You can disregard the content below this point.

Another issue to note is that even after fixing your loader, you may still encounter loading difficulties.

When dealing with images, it's recommended to use the img tag for loading them.

<img :src=`require(...)`/>

The v-html attribute will only load the path string itself.

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

Looking to retrieve object values in JavaScript in a dynamic manner?

Imagine having an array of objects with nested objects. The data is always changing, meaning the keys may vary each time. For instance: [ { "uuid": "53e7202c-28c8-4083-b910-a92c946a7626", "extraIdentifiers": { "National ID": "NAT2804" }, ...

Creating a real-time email validation system that incorporates both syntax and domain checking

I recently came across a helpful example on that guided me in implementing basic validation for emails and usernames. This led me to another demonstration where ajax was used to call a live email checker PHP script. However, I've hit a roadblock whe ...

Angular sends a blank object to the server

Utilizing angular along with spring boot 2 has presented a challenge for me. Each time I attempt to send a POST request, spring validation messages pop up indicating that my fields cannot be empty or null. Here is the form structure of my POST request: < ...

Manipulating checkboxes with Jquery

I have set up a scenario with two divs and two checkboxes. When the first checkbox is clicked, the first div will appear. Subsequently, if the second checkbox is clicked, the second div will appear below the first div. I initially styled both divs. Howev ...

Tips for locking the button in the navigation bar while scrolling

I noticed that when I have 6 fields in my navbar, with 5 of them being links and one as a dropdown, the scrolling of the page causes all fields to remain fixed except for the dropdown field.Check out this image description for reference https://i.stack.im ...

I'm having trouble extracting text from the HTML code for an unknown reason

My code seems to be working well until I attempt to use the .text function, resulting in an error message stating "list' object has no attribute 'text". Interestingly, when I apply .text to a single element within the same list, it works without ...

Strategies for efficiently creating reusable HTML templates for recurring content blocks?

I am just starting out in web development and have encountered a problem with navigating through my page. The layout of the pages is the same, except for a div container. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

Saving an array within the Yii framework

The view contains the following form: <form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data"> <label>Upload your photo:</label><input type="fi ...

What steps can be taken to fix a syntax error in a NodeJS express server code?

I am currently facing a syntax error in the code below, and I'm struggling to fix it. The specific error message is as follows: node staticapi.js /Users/v/Desktop/CS-Extra/EIP/A5/staticapi.js:123 res.status(200).send("Api is running") ...

Enabling Cross-Origin Resource Sharing (CORS) with Javascript on the client side during

Currently, I am attempting to incorporate another website's login verification system into my own site. Although the code below is successfully retrieving the correct response ID, I am encountering CORS errors preventing the completion of the login pr ...

Prevent issues with text overlap in HTML and CSS

My text is overlapping when I resize the window. How can I prevent this? I want the text to resize only if it collides with other elements, or stack under each other if resizing is not possible. problem I've already attempted using flex box setting ...

menu fails to expand when clicked in mobile view

Could someone please help me troubleshoot why the menu icon is not expanding in mobile view? I'm not sure what I did wrong. Here is the link for reference: Snippet of HTML: <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> ...

Change element's parent property's child property into an array form

Question 1: Do you believe that element.property is the same as element[property]? If your answer to question 1 is affirmative, then move on to Question 2: Can you convert element.parentProperty.childProperty into array syntax as explained in question ...

Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application. My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once t ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...

Creating a CSS Grid with Scroll Snap functionality to mimic an iPhone screen in HTML

I have created an iPhone simulator using HTML. It's in German, but I can provide a translation if needed: // JavaScript code for various functionalities related to the iPhone interface /* CSS styling for the iPhone interface */ <meta name="v ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

"Troubleshooting an issue with post requests in VueJS and Laravel resulting in

Trying to execute a basic POST request using VueJS 2 (with axios) and Laravel 5.3, but encountering an issue where my method consistently returns an empty array when attempting to print $request->all(). The blade template includes the following meta ta ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

Adding a CSS style to a specific child element

Here is an example snippet <html> <head> <style> .test > input { //this selector is incorrect. color:red; } </style> </head> <body> <div class="test"> <di ...