Home  >  Article  >  Web Front-end  >  How to Dynamically Display Images in Vue.js with Computed Properties and Webpack?

How to Dynamically Display Images in Vue.js with Computed Properties and Webpack?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 21:34:02722browse

How to Dynamically Display Images in Vue.js with Computed Properties and Webpack?

Dynamic Image Display in Vue.js Using Webpack

In a Vue.js application utilizing webpack, you may encounter challenges when attempting to dynamically display images whose filenames are stored in computed properties. Specifically, if these properties depend on asynchronously populated Vuex store variables, you might observe that image paths are not being resolved correctly.

Consider the following Vue template:

<div class="col-lg-2" v-for="pic in pics">
  <img v-bind:src="'../assets/' + pic + '.png'" v-bind:alt="pic">
</div>

While this approach works flawlessly when a static image path is provided (e.g., How to Dynamically Display Images in Vue.js with Computed Properties and Webpack?), it fails to display the image when the path is dynamically generated from a computed property. Similar issues have been reported and resolved in this fiddle.

To resolve this issue, you can employ the following JavaScript code:

getImgUrl(pet) {
  var images = require.context('../assets/', false, /\.png$/)
  return images('./' + pet + ".png")
}

This function utilizes webpack's require.context() to dynamically load images from a specific directory based on the provided filename.

In the HTML template, the v-bind:src attribute should be updated to reference the getImgUrl() function instead of generating the path directly:

<div class="col-lg-2" v-for="pic in pics">
  <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

By implementing this solution, you can dynamically display images in your Vue.js application with webpack, even if the image filenames are stored in computed properties.

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

Statement:
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