-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (92 loc) · 2.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const STRATEGY_MAP = {
'async': function (callback) {
setTimeout(() => callback(), 300)
},
'viewport': function (callback) {
const windowHeight = window.innerHeight
const check = () => {
const { top } = this.$refs['lowerComponent'].getBoundingClientRect()
if (windowHeight + 30 >= top) {
callback()
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
check()
}, 100)
}
check()
this.$once('hook:beforeDestroy', () => {
clearTimeout(this.timer)
})
}
}
export default {
name: 'lower-component',
props: {
level: {
type: String,
default: 'async'
},
custom: {
type: [Function, Boolean],
default: () => Promise.resolve()
}
},
data () {
return {
isRender: false
}
},
mounted() {
if (this.level === 'custom') {
if (typeof this.custom === 'function') {
const customPromise = this.custom()
if (process.env.NODE_ENV !== 'production') {
if (typeof customPromise.then !== 'function') {
throw new Error('当custom是函数类型时,custom必须返回一Promise')
}
}
customPromise.then(() => {
this.updateLevel()
})
return
}
const unwatch = this.$watch(() => this.custom, (newVal) => {
if (newVal) {
this.updateLevel()
this.$nextTick(() => {
unwatch()
})
}
}, {
immediate: true
})
return
}
if (process.env.NODE_ENV !== 'production') {
if (!STRATEGY_MAP.hasOwnProperty(this.level)) {
throw new Error('不支持的升级策略')
}
}
STRATEGY_MAP[this.level].call(this, this.updateLevel)
},
methods: {
updateLevel () {
this.isRender = true
}
},
render (h) {
if (this.isRender) {
if (this.$slots.default) {
return this.$slots.default[0]
}
return this._e()
}
if (this.level === 'viewport') {
return h('div', {
ref: 'lowerComponent'
})
}
return this._e()
}
}