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

How to Dynamically Display Images in Vue.js Applications with Webpack?

Susan Sarandon
Release: 2024-11-14 15:21:02
Original
599 people have browsed it

How to Dynamically Display Images in Vue.js Applications with Webpack?

Displaying Dynamic Images in Vue.js Applications with Webpack

In Vue.js applications, rendering dynamic images can prove challenging when images are stored in variables and accessed through file paths. To overcome this, developers commonly encounter issues when using v-bind:src with computed values that retrieve image file names.

Original Method:

<img v-bind:src="'../assets/' + pic + '.png'" v-bind:alt="pic">
Copy after login

Problem:

This approach doesn't render dynamic images when the image file name is stored in a variable.

Solution:

To resolve this, a custom method getImgUrl can be defined to dynamically retrieve the image URL and bind it to the src attribute of the img element.

methods: {
  getImgUrl(pet) {
    var images = require.context('../assets/', false, /\.png$/)
    return images('./' + pet + ".png")
  }
},
Copy after login
<!-- HTML -->
<img :src="getImgUrl(pic)" v-bind:alt="pic">
Copy after login

Why the Original Method Failed:

The original method failed because Vue.js was unable to resolve the file path string dynamically. The require.context function allows Vue to access static assets within the application, making the getImgUrl method a more reliable solution.

The above is the detailed content of How to Dynamically Display Images in Vue.js Applications 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