Reputation: 445
I have configured Vite with an alias "@"
as "./src"
.
Using the alias directly as <img>.src
is ok:
<!-- this is ok -->
<img src="@/assets/icon-1.svg">
but passing the src
as a prop is not working:
<!-- ComponentA -->
<template>
<img :src="imgSrc">
</template>
<!-- Parent Component: alias not resolved as expected; imgSrcWithAlias is "@/assets/icon-1.svg" -->
<component-a :img-src="imgSrcWithAlias" />
Is there any solution to use file path alias when passing props?
Upvotes: 3
Views: 4196
Reputation: 51
@tony19 Answer was what works for me. Using Vue 3 with Vite + TypeScript (Js should work too!) The only difference, is that if aren't using a script with the "setup" attribute: You need to import the image, and return it inside the export default. See:
<script lang="ts">
import { defineComponent } from 'vue'
//Import the images:
import feedImg from './assets/img/feed.png'
export default defineComponent({
setup() {
//Return the imgs:
return {
feedImg
}
}
})
</script>
After that, you just need to bind the image to the prop on the component usage:
<ImageComponent
:imgSrc="feedImg"
alt="Videos on homepage"
/>
And load it on the component itself, binding the src on the img tag:
<template>
<img :alt="alt" :src="imgSrc" />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
props: {
imgSrc: {
type: String,
required: true
},
alt: {
type: String,
required: true
}
}
})
</script>
Upvotes: 0