How to Use Vue Lazyload in a Vue Project demo repo
Vue Lazyload (opens new window) is a Vue.js plugin for lazyloading image or component.
WARNING
Vue Lazyload is not compatible with Vue 3 at the time of this writing, so this tutorial is only for Vue 2.
# 👣 Steps
- Create a Vue project and install Vue Lazyload.
npm i -g @vue/cli
vue create vue2-demo
cd vue2-demo
npm i vue-lazyload
Put a placeholder image to load while loading, e.g.
src/assets/loading.svg
. Put another to load upon load fail, e.g.src/assets/error.svg
.Register Vue Lazyload and pass the options (opens new window) needed in
src/main.js
.
import VueLazyload from "vue-lazyload";
import error from "./assets/error.svg";
import loading from "./assets/loading.svg";
Vue.use(VueLazyload, {
preLoad: 1,
error: error,
loading: loading,
attempt: 1
});
- Use Vue Lazyload, e.g. in
src/views/vue-lazyload.vue
. I purposely made a typo in one of the 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.