Home > Article > Web Front-end > How to Dynamically Display 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">
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") } },
<!-- HTML --> <img :src="getImgUrl(pic)" v-bind:alt="pic">
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!