上一篇:
当我们的请求未得到响应时,展示loading,响应回来后,展示需要展示的内容。
在vue2中要想做到此目的,需要我们去写一个loading的组件,或者是骨架屏之类的,然后定义一个变量 默认为true,得到响应后更改为false,true的时候展示loading,false的时候展示我们的列表内容之类的,但是在vue3中,我们要想达到此目的会更容易点
App.vue
<template>
<div class="grand">
<h1>我是app</h1>
<Suspense>
<template v-slot:default>
<child :id="99"></child>
</template>
<template v-slot:fallback>
<div>Loading...</div>
</template>
</Suspense>
</div>
</template>
<script>
import Child from "@/components/Child.vue";
export default {
name: "App",
components: {
Child,
},
};
</script>
<style scoped>
.grand {
background-color: rgb(150, 156, 154);
padding: 50px;
}
</style>
Child.vue
<template>
<div class="child">
<h3>{{ msg }}-{{ msg1 }}</h3>
<h3>{{ otherInfo }}</h3>
</div>
</template>
<script>
import { ref } from "vue";
export default {
props: {
id: {
required: true,
type: Number,
default: null,
},
},
async setup(props) {
let otherInfo = ref("其他信息");
let msg = await getData(props.id);
let msg1 = await getData1(props.id);
function getData(id) {
console.log(id);
return new Promise((resolve) => {
setTimeout(() => {
resolve("hello");
}, 1000);
});
}
function getData1(id) {
console.log(id);
return new Promise((resolve) => {
setTimeout(() => {
resolve("world");
}, 3000);
});
}
return { otherInfo, msg, msg1 };
},
};
</script>
<style scoped>
.child {
background-color: rgb(22, 129, 201);
padding: 50px;
}
</style>
效果:
三秒之后会变为:
请注意,插槽的名称是固定的,不是随便自定义的!