Skip to content

Commit 730931b

Browse files
committed
2 parents db62ac9 + 413d8aa commit 730931b

File tree

3 files changed

+1260
-14
lines changed

3 files changed

+1260
-14
lines changed

第13章异步组件与函数式组件/12.2_异步组件的实现原理/13.2.2_超时与Error组件.html

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
<div id="app"></div>
1212
<script src="https://unpkg.com/@vue/[email protected]/dist/reactivity.global.js"></script>
1313
<script>
14-
15-
const { effect, reactive, shallowReactive, shallowReadonly } = VueReactivity
14+
const { effect, reactive, shallowReactive, shallowReadonly, shallowRef } = VueReactivity
1615
function shouldSetAsProps (el, key, value) {
1716
if (key === 'form' && el.tagName === 'INPUT') return false
1817
return key in el
@@ -94,37 +93,46 @@
9493
name: 'AsyncComponentWrapper',
9594
setup () {
9695
const loaded = ref(false)
96+
// 代表是否超时,默认为 false,既没有超时
97+
// const timeout = ref(false)
9798
// 定义 error,当错误发生时,用来存储错误对象
98-
const error = shallowRef(null)
99-
100-
loader()
101-
.then(c => {
102-
InnerComp = c
103-
loaded.value = true
104-
})
99+
const error = shallowRef(null, loaded)
100+
// 执行加载器函数,返回一个 Promise 实例
101+
// 加载成功后,将加载成功的组件赋值给 InnerComp,并将 loaded 标记为 true,代表加载成功
102+
loader().then(c => {
103+
InnerComp = c
104+
loaded.value = true
105105
// 添加 catch 语句来捕获加载过程中的错误
106-
.catch((err) => error.value = err)
107-
106+
}).catch((err) => error.value = err)
108107
let timer = null
109108
if (options.timeout) {
109+
// 如果指定了超时时长,则开启一个定时器计时
110110
timer = setTimeout(() => {
111111
// 超时后创建一个错误对象,并复制给 error.value
112-
const err = new Error(`Async component timed out after ${ options.timeout }ms.`)
112+
const err = new Error(`Async component timed out after ${ options.timeout } seconds.timeout="${ options.timeout }ms.`)
113113
error.value = err
114+
// 超时后将 timeout 设置为 true
115+
// timeout.value = true
114116
}, options.timeout)
115117
}
118+
// 包装组件被卸载时清除定时器
119+
onUmounted(() => clearTimeout(timer))
116120

121+
// 占位内容
117122
const placeholder = { type: Text, children: '' }
118123

119124
return () => {
120125
if (loaded.value) {
126+
// 如果组件异步加载成功,则渲染被加载的组件
121127
return { type: InnerComp }
128+
// } else if (timeout.value) {
122129
} else if (error.value && options.errorComponent) {
130+
// 如果加载超时,并且用户指定了 Error 组件,则渲染该组件
131+
// return options.errorComponent ? { type: options.errorComponent } : placeholder
123132
// 只有当错误存在且用户配置了 errorComponent 时才展示 Error 组件,同时将 error 作为 props 传递
124133
return { type: options.errorComponent, props: { error: error.value } }
125-
} else {
126-
return placeholder
127134
}
135+
return placeholder
128136
}
129137
}
130138
}

0 commit comments

Comments
 (0)