Skip to content

Instantly share code, notes, and snippets.

@matthewmorek
Last active June 9, 2020 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewmorek/8c7cf5b55a258d5925b77b0d7df75755 to your computer and use it in GitHub Desktop.
Save matthewmorek/8c7cf5b55a258d5925b77b0d7df75755 to your computer and use it in GitHub Desktop.
Vue Storyblok Picture Component
<template>
<picture>
<source
v-for="format in formats"
:srcset="srcset(url, sizes, format, quality)"
:alt="alt"
:key="format"
:type="`image/${format}`"
/>
<img :src="src(url, 960, 'jpg', 90)" :alt="alt" />
</picture>
</template>
<script>
export default {
props: {
url: {
type: String,
required: true,
},
alt: {
type: String,
required: true,
},
sizes: {
type: Array,
default: () => [960, 1856],
},
formats: {
type: Array,
default: () => ['webp', 'jpg'],
},
quality: {
type: Number,
default: () => 90,
},
},
methods: {
srcset: (url, sizes, format, quality) => {
if (!url) return null;
let imageService = 'https://img2.storyblok.com/';
let path = url.replace('https://a.storyblok.com', '');
let sources = [];
sizes.forEach((size, index) => {
sources.push(
`${imageService}${size}x0/filters:format(${format}):quality(${quality})${path} ${
index + 1
}x`
);
});
return sources.join(', ');
},
src: (url, size, format, quality) => {
if (!url) return null;
let imageService = 'https://img2.storyblok.com/';
let path = url.replace('https://a.storyblok.com', '');
return `${imageService}${size}x0/filters:format(${format}):quality(${quality})${path}`;
},
},
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment