Skip to content

Commit

Permalink
feat(nuxt-img): responsive prop (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Jan 25, 2021
1 parent b5031cc commit 3dcee93
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
2 changes: 1 addition & 1 deletion playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<NuxtImg src="https://nuxtjs.org/logos/nuxt.svg" width="400" height="400" />

<h2>JPEG image inside project</h2>
<NuxtImg src="/images/damavand.jpg" />
<NuxtImg responsive src="/images/damavand.jpg" />

<h2>JPEG image from remote url</h2>
<NuxtImg src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Aconcagua2016.jpg/600px-Aconcagua2016.jpg" />
Expand Down
33 changes: 31 additions & 2 deletions src/runtime/components/nuxt-img.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
:height="height"
:src="nSrc"
:alt="nAlt"
v-bind="nAttrs"
>
</template>

<script lang="ts">
import { generateAlt, useObserver } from '~image'
import { generateAlt, useObserver, parseSize } from '~image'
const EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
Expand All @@ -33,7 +34,8 @@ export default {
// options
preset: { type: String, required: false, default: undefined },
provider: { type: String, required: false, default: undefined }
provider: { type: String, required: false, default: undefined },
responsive: { type: Boolean, required: false, default: false }
},
data () {
return {
Expand All @@ -54,6 +56,15 @@ export default {
modifiers: this.nModifiers
}).url
},
nAttrs () {
const attrs: any = {}
if (this.responsive) {
const { sizes, srcSet } = this.getResponsive()
attrs.sizes = sizes
attrs.srcSet = srcSet
}
return attrs
},
nModifiers () {
return {
...this.modifiers,
Expand All @@ -66,6 +77,12 @@ export default {
}
}
},
created () {
if (process.server && process.static) {
// Force compute sources into ssrContext
this.getResponsive()
}
},
mounted () {
if (this.usePlaceholder) {
this.observe()
Expand All @@ -75,6 +92,18 @@ export default {
this.unobserve()
},
methods: {
getResponsive () {
const sizes = this.$img.getSizes(this.src, {
sizes: this.sizes,
width: parseSize(this.width),
height: parseSize(this.height),
modifiers: this.modifiers
})
return {
sizes: sizes.map(({ width }) => `(max-width: ${width}px) ${width}px`),
srcSet: sizes.map(({ width, src }) => `${src} ${width}w`)
}
},
observe () {
this._removeObserver = useObserver(this.$el, () => {
this.usePlaceholder = false
Expand Down

0 comments on commit 3dcee93

Please sign in to comment.