The require statement in Vue.js is failing to function dynamically

Having trouble dynamically requiring an image in Vue.js and it's not functioning as expected

 <div class="card" :style="{ background: 'url(' + require(image) + ')',}">



    export default {
      data() {
      return {
        image: "./assets/dance.jpg",
    };
  }
};

Answer №1

<div class="image-section" :style="{ backgroundImg: 'url(' + image + ')' }">

Answer №2

It is recommended to include the require statement in the data instead of directly in the html template.

This approach is beneficial because Webpack scans all require statements and resolves them during compilation, rather than at runtime. This enables webpack to eliminate unused images from your build or even convert them into data urls.

<div class="card" :style="{ background: 'url(' + image + ')',}">

export default {
    data() {
        return {
            image: require("./assets/dance.jpg"),
        };
    }
};

Note that requires are resolved based on the path of your .vue file, not the project root. If you begin the path with @/, you can reference files from the src directory.

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

How to programmatically update one input value in AngularJS and trigger validation as if it was manually entered by the user?

I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...

When resizing an anchor tag with a percentage in CSS, the child image width may not scale accordingly

In short, I have multiple draggable images on a map enclosed in anchor tags (<a><img></a>) to enable keyboard dragging. The original image sizes vary, but they are all too large, so I reduced them to 20% of their original sizes using the ...

Can a single component support multiple v-model bindings simultaneously?

Having a component used in two different places with an <input v-model="model" >, I face the challenge of watching this v-model in my component. The issue arises as the model changes - one place has model = array.val1 while the other has model = arra ...

"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice. I have come across some threads discussing sending just an image, but not integrating an image within a JSON data o ...

How can we limit the files served from an Express static directory to only .js files?

I'm curious to know if it's doable to exclusively serve one specific type of file (based on its extension) from an Express.js static directory. Imagine having the following Static directory: Static FileOne.js FileTwo.less FileThree. ...

React: Encountered an expression in JSX where an assignment or function call was expected

Trying to build a left-hand menu for my test application using react. Encountering a compilation error in the JSX of one of my classes. Is it because HTML elements cannot be placed within {} scripts in JSX? If so, how do I fix this? ./src/components/Left ...

Is it possible to define a data type from an external package using TypeScript and Node.js?

I'm currently in the process of reorganizing some code to utilize a list of signals and connect `.once` handlers to each one individually. const terminationSignals = ["SIGINT", "SIGUSR2", "SIGTERM"]; terminationSignals.f ...

A step-by-step guide on how to verify a selection using JavaScript

Is it possible to validate the select option with JavaScript? For example, if a user selects "Admin," then the page works for admin login. If they select "Vendor," then it works for vendor login. <table class="login_table" width="100%" border="0" cells ...

Utilizing JavaScript to trigger an email with PHP variables included

i am trying to pass a few php variables using a javascript trigger. Everything seems to be working with the variables, databases, and script but I am struggling with the PHP part. Here is my attempt at the PHP code, although it clearly has some issues. I ...

Chaining promises allows you to utilize the outcome of one request to make another

I've been experimenting with ES6 in node.js and want to transition from using callbacks to promises. I created a test project to fetch an oauth2 token from an api/endpoint, refresh it, and then revoke it. My code snippet is as follows: const oauth2Ad ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Ways to showcase a standalone identifier from iTunes RSS

I have a script below that fetches iTunes charts directly from the RSS and displays it. However, I am looking to only display the information for a specific ID from the RSS entry. Any suggestions on how this can be achieved? <script> jQuery(functi ...

When using Jest, the mongoose findOneAndUpdate function may return null values for both error and document

I've been struggling with Mongoose's findOneAndUpdate method as it doesn't seem to provide any useful information. I have tried accessing the Query returned from calling it (stored in updatedUser), but all it returns is null. Adding a callba ...

Is there a reason why the Chrome browser doesn't trigger a popstate event when using the back

JavaScript: $(document).ready(function() { window.history.replaceState({some JSON}, "tittle", aHref); $(window).bind("popstate", function(){ alert("hello~"); }); }); Upon the initial loading of the www.example.com page, the above JavaScript code is ex ...

What is the best way to use AJAX to load a PHP file as a part

I'm exploring different methods for making an AJAX call with an included file. Let's create a simple working example. Initially, I have my main index.php file which contains the following content. In this file, I aim to access all the data retur ...

Retrieving the slug from the parameters in the API response using this.$route

I am currently using vue-router to navigate from an 'index' page displaying records for a particular resource. I have set up a router-link to direct you to a separate page for each individual record. Although the route is functioning correctly, I ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...