如何使用Vue方法作为图像源?

时间:2019-05-07 13:54:20

标签: image vue.js methods assets

在Vue中,我试图将方法的结果用作图像的来源:

HTML:

<img :src="getEnergyIcon(type)">

JS:

data() {
      return {

          energyTypeMap: new Map([
            ['colorless','@/assets/images/energy-icons/20px-Colorless-attack.png'],
            ['darkness','@/assets/images/energy-icons/20px-Darkness-attack.png'],
            ['dragon','@/assets/images/energy-icons/20px-Dragon-attack.png'],
            ['fairy','@/assets/images/energy-icons/20px-Fairy-attack.png'],
            ['fighting','@/assets/images/energy-icons/20px-Fighting-attack.png'],
            ['fire','@/assets/images/energy-icons/20px-Fire-attack.png'],
            ['grass','@/assets/images/energy-icons/20px-Grass-attack.png'],
            ['lightning','@/assets/images/energy-icons/20px-Lightning-attack.png'],
            ['metal','@/assets/images/energy-icons/20px-Metal-attack.png'],
            ['psychic','@/assets/images/energy-icons/20px-Psychic-attack.png'],
            ['water','@/assets/images/energy-icons/20px-Water-attack.png'],
            ])

      }
    },

并且:

methods: {
        getEnergyIcon(type){
            return this.energyTypeMap.get(type.toLowerCase());
        }
    },

该方法返回正确的路径,但是图像未使用该路径作为源:

enter image description here

我希望结果与硬编码结果相同,但是我想通过使用该方法来实现这一点,因为我将使用动态数据,该数据为我提供了11种类型之一,因此我无法使用硬编码路径。

我一直在Google搜索中寻找解决方案,但找不到使用直接方法作为图像源的解决方案。我该怎么做?

谢谢。

1 个答案:

答案 0 :(得分:1)

找到了这个话题:

How to reference static assets within vue javascript

其中提到以下内容:

  

在Vue常规设置中,/ assets不提供。

     

图像将改为src =“ ...”字符串。

并要求我使用:

require();

我确实这样:

data() {
      return {
          card: {},
          energyTypeMap: new Map([
            ['colorless',require('@/assets/images/energy-icons/20px-Colorless-attack.png')],
            ['darkness',require('@/assets/images/energy-icons/20px-Darkness-attack.png')],
            ['dragon',require('@/assets/images/energy-icons/20px-Dragon-attack.png')],
            ['fairy',require('@/assets/images/energy-icons/20px-Fairy-attack.png')],
            ['fighting',require('@/assets/images/energy-icons/20px-Fighting-attack.png')],
            ['fire',require('@/assets/images/energy-icons/20px-Fire-attack.png')],
            ['grass',require('@/assets/images/energy-icons/20px-Grass-attack.png')],
            ['lightning',require('@/assets/images/energy-icons/20px-Lightning-attack.png')],
            ['metal',require('@/assets/images/energy-icons/20px-Metal-attack.png')],
            ['psychic',require('@/assets/images/energy-icons/20px-Psychic-attack.png')],
            ['water',require('@/assets/images/energy-icons/20px-Water-attack.png')],
            ]) 
      }
    },

它解决了我的问题。