1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 微信小程序封装懒加载图片

微信小程序封装懒加载图片

时间:2021-05-13 01:27:21

相关推荐

微信小程序封装懒加载图片

微信小程序封装懒加载图片

js

/components/LazyImage/index.js

// components/LazyImage/index.jsComponent({/*** 组件的属性列表*/properties: {// 图片urlsrc: {type: String,value: '//05/08/OlbiFI.gif'},// "加载中"图片urllazyImageUrl: {type: String,value: '//05/08/OlbiFI.gif'},// modemode: {type: String,value: 'widthFix'},},/*** 组件的初始数据*/data: {imageId: ""},lifetimes: {// 在组件在视图层布局完成后执行async ready() {// 生成唯一 imageIdconst imageId = 'image' + Date.now();this.setData({imageId});// 开启懒加载this.lazy('.' + imageId);}},/*** 组件的方法列表*/methods: {// 懒加载lazy(className) {const root = this;const IntersectionObserver = this.createIntersectionObserver();IntersectionObserver.relativeToViewport();IntersectionObserver.observe(className, async (res) => {if (res.intersectionRatio) {root.setData({lazyImageUrl: root.data.src});// 关闭监听IntersectionObserver.disconnect();}})},}})

wxml

/components/LazyImage/index.wxml

<image src="{{lazyImageUrl}}" mode="{{mode}}" class="lazy-image {{imageId}}"></image>

wxss

.lazy-image {display: block;width: 100%;}

组件已经发布到npm,移步查看wmp-lazy-image

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。