The issue arises when trying to pass the name of an image to a Vue component, but

My goal is to dynamically create an input component with a specific icon for each input. The icon is set as a background image in the CSS, and it works when directly included like this:

background-image: url(../../assets/icons/email.svg);

However, when I pass the name of the icon as a prop for the component, the app throws an error indicating that the icon is not found. https://i.sstatic.net/FYZGG.png

    <template>
        <section class="input-box">
            <input class="input-field" type="text" :style="imgIcon">
            <label>{{title}}</label>
        </section>
    </template>

    <script>
      export default {
        props: ["title", "bgImg"],
        computed: {
          imgIcon() {
            return 'background-image: url(./assets/icons/' + this.bgImg + ')';
          }
        }
      }
    </script>

When passing the name as a string:

<custome-input title="password" bgImg="'p_key.svg'"></custome-input>

The error is resolved but nothing appears on screen!

Where did I specifically go wrong?

Answer №1

It is recommended to use the require function when dynamically binding an image:

computed: {
  dynamicImage() {
    try {
      return 'background-image:url(' + require('@/assets/images/' + this.imagePath) + ')';
    } catch(error) {
      return '';
    }
  }
}

The error mentioned in the comments occurs because part of the path is based on a prop that may not be defined yet when the calculation takes place, hence the necessity for the try block.

Answer №2

To include images from templates, you must utilize the @ symbol and ensure that the url is in string format.

export default {
  props: ["title", "bgImg"],
  computed: {
    imgIcon() {
      return `background-image: url('@/assets/icons/${this.bgImg}')`;
    }
  }
}

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

Execute a command and direct the input/output to designated files

My goal is to execute a child process in the background while also modifying its output (like adding timestamps) and directing it to specific files. Currently, I am approaching this task as follows: try { var out = fs.createWriteStream(`${this.logdir}/$ ...

Ipad not retaining Express session data

Having trouble with saving a session variable for a user when they log in. Strangely, it works fine on the computer but not on an iPad using Safari or Chrome. Below is my session setup: app.set('trust proxy', 1) app.use(session({ secret: cryp ...

incorporating video content onto a webpage

Let me provide more details for better understanding. Currently, the website is not operational yet. Once it's live, I'll be hosting it on a platform like YouTube. The issue I encountered was when trying to embed a video using the code below: & ...

What is the reason for Python Flask to consume both instances of a file when using .decode()?

In my program, I am fetching a CSV file from an HTML form and decoding it using utf-8. However, I need to have two instances of this file for different purposes. The issue arises when I use .decode('utf-8'), as both instances end up being consume ...

Select a specific division element using a pseudo element

My goal is to specifically target the third div in my HTML code with a class called .counter-wrap. When viewed on a mobile device, this particular div has a margin-bottom of 40px. I am looking to eliminate the margin-bottom for only the third stacked div n ...

Arranging an array containing three elements

As I work on my angular app, I have come across the following array: [ { "Name": "Jack", "IncomingTime": "2020-06-19T11:02+00:00", "Outgoingtime": "2020-06-19T11:07+00:00" ...

The dilemma between Nuxt Js global CSS and Local CSS

Currently, I am in the process of developing a Nuxt application utilizing an admin template. While I am well-versed in Vue.js, I am finding the aspect of loading assets within Nuxt.js to be a bit perplexing. I am in the process of converting the admin temp ...

Is there a way to directly import a client's .STL file into a three.js scene without having to load it from the

I am trying to implement a 'choose file' button that allows users to load files on the client side instead of from the server path in loader.load() on line 86. It seems like I might need to utilize the File API for this, but I'm still unsure ...

There is an unseen culprit lurking in the white void on the right side of the website

Does anyone else notice a mysterious blank space on the right side of my website? Even though the content spans 100% across the site and looks fine, there seems to be an extra margin when you scroll to the right, whether you're on a desktop or mobile ...

Is there an easy method to reposition the rotation pivot of an Object3D in Three.js?

Is there a straightforward method to change the rotation pivot of THREE.Object3D? By default, the pivot point is the position point of the object. I have a group (implemented as THREE.Object3D) of objects and I want to rotate all objects together around a ...

What situations warrant the choice of an Isomorphic JavaScript application?

Recently, there has been an increase in tutorials and examples discussing Isomorphic web applications with react.js. As a beginner myself, I find it challenging to determine whether this is necessary or not. For instance, my application will primarily be ...

How do I retrieve the download URL for the file created using Python in my Heroku App?

After developing my Flask App, I uploaded several files to the Heroku filesystem. I'm aware that these files are removed every time the dyno restarts. Now, in my HTML/JavaScript frontend, I'd like to provide users with a download button for thes ...

In order to display the new component upon the first click in React, my button requires a double click

I have a project that utilizes the open Trivia API to fetch data. I've completed the development and everything appears to be working well so far. However, there's a bug where upon initially rendering the app, the first time I click the button to ...

Utilize Express and Mongodb to interact with API and database queries

Looking for assistance with my project on creating a gaming server list. Users should be able to add their server by entering a title, IP, port, and some information about it. However, on the homepage, I also want to display the number of players and whet ...

How can I declaratively bind the properties in Dojo's _hasDropDown method?

UniqueSearchComponent.html: <div class="${baseClass}"> <div data-dojo-type="dijit/_HasDropDown" data-dojo-props="dropDown: 'containerNode'"> <div data-dojo-type="dijit/form/TextBox" name="${SearchViewFieldName} ...

Leveraging Firebase in Electron Applications

I've been experimenting with integrating Firebase into Electron. However, I've run into a roadblock when trying to set it up similar to how I would on a regular web page. Since Electron pages are hosted locally and lack a hostname, the usual setu ...

Having difficulty recreating the arrow feature in the bootstrap sidebar

I am currently working on creating the fourth sidebar (from the left) using the templates provided in Bootstrap 5 examples. Everything seems to be falling into place except for one issue - I can't seem to get the arrow to rotate when aria-expanded=tr ...

Swapping AngularJS module parameters for testing

Within my module, there exists a greet factory that is attached: angular.module('someModule', []) .factory('greet', function(name) { return function() { return 'Hi ' + name + '!'; } }); This facto ...

Is using display:table an effective approach for achieving equal height columns?

I am currently working on a responsive design project and I need two columns of equal height. I do not want to rely on JavaScript for this, and I prefer having some whitespace between the columns to enhance readability. I have tried two different layouts; ...

Creating a line chart with chart.js using AJAX - step by step guide

I've been attempting to create a line chart using chart.js in conjunction with AJAX, but I haven't had much success so far. The chart works perfectly when submitted through a normal form or on window load, but it fails to plot when utilizing AJAX ...