Reputation: 629
I am using VueJS via VUE CLI and have a component called Icon.vue. This component has a variable which should be set by the App.vue file. How can i achieve this?
This is my App.vue file:
<template>
<div id="app">
<Icon iconUrl="../assets/img/plant-icon-1.svg" iconAlt="Blume"/>
</div>
</template>
<script>
import Icon from './components/Icon.vue'
export default {
name: 'app',
components: {
Icon
}
}
</script>
and there's my Icon.vue file:
<template>
<div class="container iconBar">
<div class="row">
<div class="col text-center py-5">
<img :src="{ iconUrl }" :alt="{ iconAlt }">
</div>
</div>
</div>
</template>
What am i missing? Nothing is generated in the frontend. It's just empty.
As suggested i edited my Icon.vue like this. But still NO output. In the frontend i get an empty image and an [object Object]
output in the alt-Tag
<template>
<div class="container iconBar">
<div class="row">
<div class="col text-center py-5">
<img :src="{ iconUrl }" :alt="{ iconAlt }">
</div>
</div>
</div>
</template>
<script>
export default {
props: {
iconUrl: {
type: String,
required: true
},
iconAlt: {
type: String,
required: true
}
}
}
</script>
Now it works. The fault was that i called an object and not the string. Therefore you have to write
<img :src="iconUrl" :alt="iconAlt">
instead of
<img :src="{ iconUrl }" :alt="{ iconAlt }">
Thanks everyone!
Upvotes: 0
Views: 1310
Reputation: 1612
Add a prop to the Icon component, like so:
<template>
<div class="container iconBar">
<div class="row">
<div class="col text-center py-5">
<img :src="iconUrl" :alt="iconAlt">
</div>
</div>
</div>
</template>
<script>
export default {
props: ['iconUrl', 'iconAlt']
}
</script>
take a look at the documentation: https://v2.vuejs.org/v2/guide/components-props.html
You could also add validation to it to ensure it's supplied and is a string:
<script>
export default {
props: {
iconUrl: {
type: String,
required: true
}
}
}
</script>
Upvotes: 2
Reputation: 2761
Consider not using camelcase convention to call props in your component instead use kebab-case like this:
Vue.component('icon-component', {
props: ['iconName', 'iconAlt'],
data () {
return {
iconUrl: '../assets/img/' + this.iconName + '.svg'
}
},
template: `
<div class="container iconBar">
<div class="row">
<div class="col text-center py-5">
<img :src="iconUrl" :alt="iconAlt">
<p>icon url path: {{ iconUrl }}</p>
</div>
</div>
</div>
`,
})
new Vue({
el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<icon-component
icon-name="plant-icon-1"
icon-alt="Blume"
/>
</div>
Upvotes: 1
Reputation: 13
In your Icon.vue file, add your props.
<template>
<div class="container iconBar">
<div class="row">
<div class="col text-center py-5">
<img :src="{ iconUrl }" :alt="{ iconAlt }">
</div>
</div>
</div>
</template>
<script>
export default {
props: ['iconUrl', 'iconAlt'],
}
</script>
Upvotes: 1