Reputation: 809
I am trying to create input component dynamically as I need for each input a specific icon for it.
Icon is set to the input as a background image and it works when I use it directly in css like so background-image: url(../../assets/icons/email.svg);
But when I pass the name of the icon for the component, the app says that it is not found!
<template>
<section class="input-box">
<input class="input-field" type="text" :style="imgIcon">
<label>{{title}}</label>
</section>
</template>
<script>
export default {
props: ["title", "bgImg"],
computed: {
imgIcon() {
return 'background-image: url(./assets/icons/' + this.bgImg + ')';
}
}
}
</script>
and when I pass the name as a string
<custome-input title="password" bgImg="'p_key.svg'"></custome-input>
the error is solved but nothing shows!
What is wrong exactly?
Upvotes: 1
Views: 326
Reputation: 63059
Use require
when binding to a dynamic image:
computed: {
imgIcon() {
try {
return 'background-image: url(' + require('@/assets/icons/' + this.bgImg) + ')';
} catch(error) {
return '';
}
}
}
The error you mentioned in comments is because part of the path is a prop that may not be defined yet when this first calculates, so it's wrapped in a try
block.
Upvotes: 1
Reputation: 6058
If you want to use images from templates you need to use @
and the url
should be a string.
export default {
props: ["title", "bgImg"],
computed: {
imgIcon() {
return `background-image: url('@/assets/icons/${this.bgImg}')`;
}
}
}
Upvotes: 1