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中文網其他相關文章!