首頁  >  文章  >  web前端  >  如何使用Webpack在Vue.js應用程式中動態顯示影像?

如何使用Webpack在Vue.js應用程式中動態顯示影像?

Susan Sarandon
Susan Sarandon原創
2024-11-14 15:21:02518瀏覽

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">

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.

以上是如何使用Webpack在Vue.js應用程式中動態顯示影像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn