Théo Lavaux
Théo Lavaux

Reputation: 1454

Vue require dynamic image

I've created this Vue component and pass it an icon path.

<CTA type="primary" icon="~/assets/phone/img/icons/share.svg" icon-alt="share">
  Primary CTA
</CTA>

My setup method returns the following

setup(props) {
  return {
   ctaIcon: props.icon,
  }
},

So ctaIcon equals ~/assets/phone/img/icons/share.svg.

When I try to use ctaIcon in the template, this works

<img :src="require('~/assets/phone/img/icons/share.svg')" />

But this doesn't work

<img :src="require(ctaIcon)" />

I get the following error Cannot find module '~/assets/phone/img/icons/share.svg'

How to get it to work properly ?

Upvotes: 2

Views: 1650

Answers (1)

Salvino D&#39;sa
Salvino D&#39;sa

Reputation: 4506

You can use a computed property to calibrate the url of asset as follows:

<script>
export default {
  props: ["ctaIcon"],
  computed: {
    mIconURL() {
      return require(`~/assets/icons/${this.ctaIcon}.png`);
    }
  }
};
</script>

Then in your code you can directly use the computed property as a variable:

<img :src="mIconURL" />

If you have multiple icons whose paths need to be resolved then, you could even create a method instead of a computed property that takes in an icon name as argument. The icon name can then be pass dynamically to the method from the tag level as follows:

<img :src="mIconURL(this.ctaIcon)" />

Upvotes: 7

Related Questions