Vue.js 中的渐进式图像加载

如果你花了任何时间在中间(我知道你有,你是一个开发者),你可能至少注意到他们的图像加载技术. 首先一个非常低分辨率的图像被加载,然后显示给客户端高度模糊的作为一个位置持有人。

(如果您有兴趣了解更多有关该技术和替代方案的信息,请查看 José M. Pérez 的此帖子(https://jmperezperez.com/medium-image-progressive-loading-placeholder/)。

显然,有一个Vue插件(由 @ccforward)实现了这种效果。

安装

在 Vue.js 项目中使用 Yarn或 NPM 安装渐进图像:

1# Yarn
2$ yarn add progressive-image
3# NPM
4$ npm install progressive-image --save

您需要先导入 CSS 到您的页面,使用您想要的任何方法(最基本的方法是直接导入)。

1<link href="./node_modules/progressive-image/dist/index.css" rel="stylesheet" type="text/css">

现在,在应用程序的主要文件中,启用ProgressiveImage插件。

 1[label main.js]
 2import Vue from 'vue';
 3import ProgressiveImage from 'progressive-image/dist/vue'
 4import App from 'App.vue';
 5
 6Vue.use(ProgressiveImage, {
 7  removePreview: true
 8});
 9
10new Vue({
11  el: '#app',
12  render: h => h(App)
13});

使用

从那时起,将预览添加到您的组件中是件好事,假设您已经准备了一张全尺寸和低分辨率的图像,

1<template>
2  <div class="my-component">
3    <!-- Render a progressive image -->
4    <div class="progressive">
5      <img class="preview" v-progressive="'./example.png'" src="https://cdn.jsdelivr.net/gh/andsky/tutorials-images/./example-preview.png"/>
6    </div>
7
8  </div>
9</template>

绑定是完全支持的,所以还可以从数组或数据集中渲染图像。

奖金:支持。

作为一个额外的奖金,渐进式图像支持对响应图像的 srcset 使用(如果你不熟悉它是什么,这里有一个关于该主题的伟大文章(https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/)。

您可以通过数据属性或约束来直接使用它。

1<template>
2  <div class="my-component">
3    <!-- Render a progressive image -->
4    <div class="progressive">
5      <img class="preview" v-progressive="'./example.png'" src="https://cdn.jsdelivr.net/gh/andsky/tutorials-images/./example-preview.png" data-srcset="./example.jpg 1x, ./[email protected] 2x"/>
6    </div>
7
8  </div>
9</template>

玩得很开心,超简单,看起来很响应的图像!

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