How to Use Vue Lazyload in a Nuxt Project demo repo
Vue Lazyload (opens new window) is a Vue.js plugin for lazyloading image or component.
# 👣 Steps
- Create a Nuxt project and install Vue Lazyload.
npx create-nuxt-app nuxt-demo
cd nuxt-demo
npm i vue-lazyload
Put a placeholder image to load while loading, e.g.
/assets/loading.svg
. Put another to load upon load fail, e.g./assets/error.svg
.Create Vue Lazyload plugin in
plugins/vue-lazyload.js
. Pass the options (opens new window) you need there as well.
import Vue from "vue";
import VueLazyload from "vue-lazyload";
import error from "../assets/error.svg";
import loading from "../assets/loading.svg";
Vue.use(VueLazyload, {
preLoad: 1,
error,
loading,
attempt: 1
});
- Register the plugin in
nuxt.config.js
.
export default {
plugins: ["@/plugins/vue-lazyload"]
};
- Use Vue Lazyload, e.g. in
pages/vue-lazyload.vue
. I purposely made a typo in the first link so you can see how an error is shown in the demo.
<template>
<div>
<h1>Vue Lazyload Demo</h1>
<div class="grid">
<b-card
v-for="(item, index) in img"
:key="index"
class="border-primary card"
>
<b-img v-lazy="item" fluid />
</b-card>
</div>
</div>
</template>
<script>
export default {
data() {
return {
img: [
"https://placeimg.co/450/450/animals",
"https://placeimg.com/450/450/arch",
"https://placeimg.com/450/450/nature",
"https://placeimg.com/450/450/people",
"https://placeimg.com/450/450/tech"
]
};
}
};
</script>
<style lang="scss" scoped>
.grid {
display: grid;
row-gap: 2rem;
@media (min-width: 768px) {
grid-template-columns: 1fr 1fr;
column-gap: 2.5rem;
}
}
.card {
display: flex;
align-items: center;
justify-content: center;
}
</style>
# 📖 Explanation
# Settings
attempt
limits the attempt to load images.error
shows a replacement image upon load fail.loading
shows another image while loading.preLoad
makes the pre-loading height the same as the actual image.
# Usage
- Lazyload (opens new window) images with
v-lazy
directive.