引入
Lazyload 是 Vue 指令,使用前需要对指令进行注册。
import { createApp } from 'vue';
import { Lazyload } from 'vant';
const app = createApp();
app.use(Lazyload);
// 注册时可以配置额外的选项
app.use(Lazyload, {
lazyComponent: true,
});
图片懒加载.
在组件中使用,把所有img的src换成v-lazy
<div class="title-box">
<img class="thumb" src="http:..." /> 替换
<img class="thumb" v-lazy="http:..." />
</div>
背景图懒加载
和图片懒加载不同,背景图懒加载需要使用 v-lazy:background-image,值设置为背景图片的地址,需要注意的是必须声明容器高度。
<div v-for="img in imageList" v-lazy:background-image="img" />
组件懒加载
将需要懒加载的组件放在 lazy-component 标签中,即可实现组件懒加载。
// 注册时设置`lazyComponent`选项
app.use(Lazyload, {
lazyComponent: true,
});
<lazy-component>
<img v-for="img in imageList" v-lazy="img" />
</lazy-component>