Add support for dynamic images
mseele opened this issue · 1 comments
Is there any possibility to load dynamic images? I have the following use case:
I load a list of events from my headless cms. All events have an attribute title image that is named like an image i have in my assets folder. Now i want to use vite-plugin-image-presets with the picture vue sfc and the image described in the event attribute.
Is there any pattern i can use to do this?
My workaround is a sfc called DynamicPicture
that looks like this:
<template>
<Picture :src="src" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
import event_img_1 from '@/assets/events/event_img_1.jpg?preset=full'
import event_img_2 from '@/assets/events/event_img_2.jpg?preset=full'
import event_img_3 from '@/assets/events/event_img_3.jpg?preset=full'
let assets = new Map<string, any>([
['event_img_1.jpg', event_img_1],
['event_img_2.jpg', event_img_2],
['event_img_3.jpg', event_img_3],
])
const props = defineProps({
name: {
type: String,
required: true,
},
})
const src = computed(() => assets.get(props.name))
</script>
It works. But i need to add a line of code every time i add a new event image into the assets directory (what happens sometimes).
Unfortunately, Vite currently does not support passing query parameters in glob imports, which would be an automatic way to generate a similar structure to the map in your example. It might add it in the future, perhaps you can suggest it as a feature request in Vite.
This plugin does provide a programmatic API that can be used directly:
const image = await images.api.resolveImage('@/assets/events/${imageName}`, { preset: 'full' })
For certain use cases this is a reasonable approach, such as when using extendFrontmatter
in îles.
Moving this to discussions, feel free to ask additional questions.