Last active
June 9, 2020 12:12
-
-
Save matthewmorek/8c7cf5b55a258d5925b77b0d7df75755 to your computer and use it in GitHub Desktop.
Vue Storyblok Picture Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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