使用 vue-clazy-load 在 Vue.js 中缓慢加载图像

图像是网页开发的一个有趣的部分。它们看起来很棒,几乎在每个应用程序或网站中都非常重要,但它们是巨大的和慢的。 晚期的一种常见技术是当它们进入视图端口时懒散地加载图像。 这节省了很多时间来加载您的应用程序,并且只加载您需要看到的图像。 对于Vue.js,有许多懒散加载解决方案,但我目前最喜欢的是 vue-clazy-load

它基本上是一个简单的插槽包装器,允许您显示自定义图像和自定义位置。

安装

在您的 Vue.js 项目中安装 vue-clazy-load。

1# Yarn
2$ yarn add vue-clazy-load
3
4# NPM
5$ npm install vue-clazy-load --save
 1[label main.js (Partial)]
 2import Vue from 'vue';
 3import App from 'App.vue';
 4import VueClazyLoad from 'vue-clazy-load';
 5
 6...
 7
 8Vue.use(VueClazyLoad);
 9
10...
11
12new Vue({
13  el: '#app',
14  render: h => h(App)
15});

由于 vue-clazy-load 使用了全新的 IntersectionObserver API,所以你可能想要一个在大多数浏览器中支持的 polyfill。

1<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>

使用

现在您可以直接使用 组件,如下所示。

 1[label App.vue]
 2<template>
 3  <div id="app">
 4    <!-- The src allows the clazy-load component to know when to display the image. -->
 5    <clazy-load src="https://cdn.jsdelivr.net/gh/andsky/tutorials-images/others/18e5971fcca245bc1b4884e87ea83f5f.png">
 6      <!-- The image slot renders after the image loads. -->
 7      <img src="https://cdn.jsdelivr.net/gh/andsky/tutorials-images/others/18e5971fcca245bc1b4884e87ea83f5f.png">
 8      <!-- The placeholder slot displays while the image is loading. -->
 9      <div slot="placeholder">
10        <!-- You can put any component you want in here. -->
11        Loading....
12      </div>
13    </clazy-load>
14  </div>
15</template>

这会给你一个基本的潜水,一旦元素进入视图端口,显示 Loading...直到图像加载,然后显示图像。

当然,有一些你可以通过的优惠:

......................................................................................................................................................................................................

还提供了一个单一的事件,负载事件,这就是,正如名字所暗示的那样,当图像完成加载时发出的事件。

同样值得注意的是,您可以有效地使用插槽中的任何组件,包括Vue过渡组件,如下所示:

 1<template>
 2  <div id="app">
 3    <!-- Boom: Free fade transitions. -->
 4    <clazy-load src="https://cdn.jsdelivr.net/gh/andsky/tutorials-images/others/18e5971fcca245bc1b4884e87ea83f5f.png">
 5      <transition name="fade">
 6        <img src="https://cdn.jsdelivr.net/gh/andsky/tutorials-images/others/18e5971fcca245bc1b4884e87ea83f5f.png">
 7      </transition>
 8      <transition name="fade" slot="placeholder">
 9        <div slot="placeholder">
10          Loading....
11        </div>
12      </transition>
13    </clazy-load>
14  </div>
15</template>
16
17<style>
18
19.fade-enter, .fade-leave-to {
20  opacity: 0;
21}
22
23</style>

我无法想象一个更简单的方法来处理图像预加载. 如果你可以,请放心向我们发送一个消息! 不过,现在,我相信Vue-clazy-load可以处理几乎任何懒惰的加载情况。

Published At
Categories with 技术
Tagged with
comments powered by Disqus