效果:
目录:
Article.vue:
<template>
<div>{{ res.title }}</div>
</template>
<script>
const getArticle = async () => {
const res = await new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve({ title: "正确加载内容!" });
} else {
reject({ msg: "呃,出了点问题~" });
}
}, 1000);
});
return res;
};
export default {
async setup() {
const res = await getArticle();
return {
res,
};
},
};
</script>
<style>
</style>
Home.vue:
<template>
<div v-if="errMsg" style="color:red;">{{errMsg}}</div>
<Suspense v-else>
<template #default>
<Article></Article>
</template>
<template #fallback>
<div>正在玩命加载中...</div>
</template>
</Suspense>
</template>
<script>
import { onErrorCaptured, reactive, toRefs } from 'vue'
import Article from '../components/Article'
export default {
components: {
Article
},
setup() {
const state = reactive({
errMsg: null
})
onErrorCaptured(e => {
state.errMsg = e.msg
})
let { errMsg } = toRefs(state)
return {
errMsg
}
}
}
</script>
<style>
</style>