Vue.js动态图片无效 [英] Vue.js dynamic images not working

查看:507
本文介绍了Vue.js动态图片无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Vue.js 中使用 webpack web应用程序时,我需要显示动态图像。我想要显示 img ,其中图像的文件名存储在变量中。该变量是返回一个 Vuex 存储变量的计算属性,该变量异步填充到 beforeMount

I have a case where in my Vue.js with webpack web app, I need to display dynamic images. I want to show img where file name of images are stored in a variable. That variable is a computed property which is returning a Vuex store variable, which is being populated asynchronously on beforeMount.

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

然而,当我这样做的时候,它可以完美运行:

However it works perfectly when I just do:

<img src="../assets/dog.png" alt="dog">

我的情况类似于 fiddle ,但这里它可以与img URL一起使用,但是在我的实际文件路径中,它不起作用。

My case is similar to this fiddle, but here it works with img URL, but in mine with actual file paths, it does not work.

什么应该是正确的方法来做到这一点?

What should be correct way to do it?

推荐答案


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

和HTML:

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

但不确定为什么我以前的方法无法正常工作。

But not sure why my earlier approach did not work.

这篇关于Vue.js动态图片无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆