How to Use Vue Lazyload in a Vue Project demo repo

Vue Lazyload is a Vue.js plugin for lazyloading image or component.

👣 Steps

  1. Create a Vue project and install Vue Lazyload.
npm i -g @vue/cli
vue create vue-demo
cd vue-demo
npm i vue-lazyload
  1. 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.

  2. Register Vue Lazyload and pass the options needed in src/main.js.

import error from "./assets/error.svg";
import loading from "./assets/loading.svg";
import VueLazyload from "vue-lazyload";
Vue.use(VueLazyload, {
  preLoad: 1,
  error: error,
  loading: loading,
  attempt: 1
});
  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">
      <div
        v-for="(item, index) in img"
        :key="index"
        class="border-primary card"
      >
        <img v-lazy="item" class="img-fluid" />
      </div>
    </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

Last updated: 7/3/2019, 11:43:37 PM