Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add isAutoDestory,and refactor the code #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 17 additions & 25 deletions src/VueLazyComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
@after-enter="(el) => $emit('after-enter', el)"
@after-leave="(el) => $emit('after-leave', el)"
>
<div v-if="isInit" key="component">
<div v-if="loading" key="component">
<slot :loading="loading"></slot>
</div>
<div v-else-if="$slots.skeleton" key="skeleton">
Expand Down Expand Up @@ -43,12 +43,15 @@
maxWaitingTime: {
type: Number,
default: 50
},
isAutoDestory: { // destory after not visible
type: Boolean,
default: false
}
},

data () {
return {
isInit: false,
timer: null,
io: null,
loading: false
Expand Down Expand Up @@ -97,44 +100,33 @@
methods: {
// 交叉情况变化处理函数
intersectionHandler (entries) {
if (
// 正在交叉
entries[0].isIntersecting ||
// 交叉率大于0
entries[0].intersectionRatio
) {
const isIntersecting = entries[0].isIntersecting || entries[0].intersectionRatio
if ( isIntersecting ) {
this.init()
this.io.unobserve(this.$el)
}else{
this.isAutoDestory && this.destory()
}
},

// 处理组件和骨架组件的切换
init () {
// 此时说明骨架组件即将被切换
this.$emit('beforeInit')
this.$emit('before-init')

// 此时可以准备加载懒加载组件的资源
this.loading = true

// 由于函数会在主线程中执行,加载懒加载组件非常耗时,容易卡顿
// 所以在requestAnimationFrame回调中延后执行
this.requestAnimationFrame(() => {
this.isInit = true
this.$emit('init')
})
this.$emit('init')
},
/**
* destory after not intersecting
*/
destory () {
this.$emit('beforeDestory')

requestAnimationFrame (callback) {
// 防止等待太久没有执行回调
// 设置最大等待时间
setTimeout(() => {
if (this.isInit) return
callback()
}, this.maxWaitingTime)
this.loading = false

// 兼容不支持requestAnimationFrame 的浏览器
return (window.requestAnimationFrame || ((callback) => setTimeout(callback, 1000 / 60)))(callback)
this.$emit('destory')
}
}
}
Expand Down