Vue.js 动态图像不起作用 [英] Vue.js dynamic images not working

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

问题描述

我有一个案例,在我的 Vue.jswebpack 网络应用程序中,我需要显示动态图像.我想显示 img 图像的文件名存储在变量中的位置.该变量是一个 computed 属性,它返回一个 Vuex 存储变量,该变量在 beforeMount 上异步填充.

<img v-bind:src="'../assets/' + pic + '.png'" v-bind:alt="pic">

但是,当我这样做时它可以完美运行:

我的情况类似于这个 fiddle,但这里它适用于 img URL,但在我的使用实际文件路径,它不起作用.

正确的做法应该是什么?

解决方案

我通过以下代码实现了这个工作

 getImgUrl(pet) {var images = require.context('../assets/', false,/.png$/)返回图像('./' + pet + ".png")}

在 HTML 中:

<img :src="getImgUrl(pic)" v-bind:alt="pic">

但不知道为什么我之前的方法不起作用.

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

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?

解决方案

I got this working by following code

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

and in 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天全站免登陆