Home > Web Front-end > JS Tutorial > How to Display Dynamic Images in Vue.js with Webpack?

How to Display Dynamic Images in Vue.js with Webpack?

Susan Sarandon
Release: 2024-11-12 05:37:01
Original
642 people have browsed it

How to Display Dynamic Images in Vue.js with Webpack?

Displaying Dynamic Images in Vue.js with Webpack

In Vue.js web applications built with webpack, displaying dynamic images can be a common requirement. However, encountering issues with this functionality can be frustrating. Let's delve into a specific scenario and explore a solution.

The Problem

In the provided code snippet, an attempt is made to dynamically display images stored in a variable How to Display Dynamic Images in Vue.js with Webpack?. The images are retrieved from a Vuex store variable, which is asynchronously populated on beforeMount. However, the dynamic image display is not functioning, while statically defined image paths work correctly.

<img v-bind:src="'../assets/'   How to Display Dynamic Images in Vue.js with Webpack?   '.png'" v-bind:alt="How to Display Dynamic Images in Vue.js with Webpack?"><br>
Copy after login

The Solution

One approach that has been found to resolve this issue is by leveraging dynamic module loading:

<br>getImgUrl(pet) {<pre class="brush:php;toolbar:false">var images = require.context('../assets/', false, /\.png$/)
return images('./' + pet + ".png")
Copy after login

}


In the HTML, the dynamic image path can be accessed using:
<br><img :src="getImgUrl(How to Display Dynamic Images in Vue.js with Webpack?)" v-bind:alt="How to Display Dynamic Images in Vue.js with Webpack?"><br>
Copy after login

This approach uses a dynamic module context to load images from a specified directory, allowing for dynamic image display.

The above is the detailed content of How to Display Dynamic Images in Vue.js with Webpack?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template