Skip to content

Instantly share code, notes, and snippets.

@deeja
Last active August 2, 2020 09:42
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 deeja/13c9ba438687aba846ae08e5ac561226 to your computer and use it in GitHub Desktop.
Save deeja/13c9ba438687aba846ae08e5ac561226 to your computer and use it in GitHub Desktop.
Lazy loading image component for Nuxt.js
<template>
<div>
<!-- Properties automatically map -->
<LazyImage class="my-class" src="/some/asset.png" alt="" />
<!-- Can use property and event binding -->
<LazyImage class="my-class" :src="transform(myObj.imageSrc)" :alt="myObj.alt" @click="showMessage" />
</div>
</template>
<template>
<img
class="lazyload"
:data-src="src"
src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII="
/>
</template>
<script>
export default {
props: {
src: { type: String, required: true }
}
};
</script>
// snippet for webpack url resolution on build
build: {
extend(config, { isClient, isDev, loaders: { vue } }) {
vue.transformAssetUrls.LazyImage = ["src", "src-set"];
}
}
// registered in the nuxt.config.js under plugins: [ "@plugins/components.js"]
import Vue from "vue";
import LazyImage from "@/components/Content/LazyImage";
Vue.component("LazyImage", LazyImage) // or even Vue.component("img-lazy", LazyImage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment