我正在读这篇文章:https://v3.vuejs.org/guide/component-dynamic-async.html#using-with-suspense
它指的是一个名为“悬浮”组件的概念。
我已经研究过了,但是我找不到任何关于什么是所谓的“悬浮”组件的信息。
有人能解释这是什么吗?谢谢!
发布于 2021-01-18 13:38:36
"Suspensible“指的是可替换的回退内容,而父<Suspense>则解析在其<template #default>中找到的async子组件。
这个概念是从React的悬念API中借用的。
更详细地说,<Suspense>是一个内置的Vue 3组件,它呈现一个<template #fallback>而不是<template #default>,直到默认模板中的所有async子组件都被解析。
为了成为可挂起的,组件的呈现需要依赖于承诺:
() => import('some/path')加载async/await函数中使用setup (或任何其他形式的承诺语法)当一个可挂组件包含在一个的默认模板中时,可挂起的组件就是,而它的父<Suspense>还没有解析它的所有可悬浮组件,即使挂起的组件本身已经解决了。
显然,<Suspense>组件本身是可悬浮的,可以嵌套悬浮。
这是Vue 3中的更详细的解释 on <Suspense>。
在其他用法中,<Suspence>提供了一种优雅而直观的方法来解决必须在v-if中包装子组件和模板的常见问题,以防止尚未加载的数据上不存在的属性。
一个典型的Vue 2例子:
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('render-items', {
props: ['items'],
template: `<table>
<tr>
<th>Id</th>
<th>User Id</th>
<th>Title</th>
</tr>
<tr v-for="(item, key) in items" :key="key">
<td v-text="item.id"></td>
<td v-text="item.userId"></td>
<td v-text="item.title"></td>
</tr>
</table>`
});
new Vue({
el: '#app',
data: () => ({
items: []
}),
computed: {
hasData() {
return this.items.length;
}
},
async created() {
const items = await fetch('https://jsonplaceholder.typicode.com/posts')
.then(r => r.json());
this.items = items;
}
})<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
<render-items :items="items" v-if="hasData"></render-items>
<template v-else>loading...</template>
</div>
使用<Suspense>和async setup在Vue 3中使用相同的示例(或多或少)
const RenderItems = Vue.defineComponent({
async setup() {
const items = await fetch('https://jsonplaceholder.typicode.com/posts')
.then(r => r.json());
return Vue.reactive({ items });
},
template: `<table>
<tr>
<th>Id</th>
<th>User Id</th>
<th>Title</th>
</tr>
<tr v-for="(item, key) in items" :key="key">
<td v-text="item.id"></td>
<td v-text="item.userId"></td>
<td v-text="item.title"></td>
</tr>
</table>`
});
const App = { components: { RenderItems }};
Vue.createApp(App).mount('#app');<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
<Suspense>
<template #default>
<render-items></render-items>
</template>
<template #fallback>
loading...
</template>
</Suspense>
</div>
一个主要的优点是在Vue 3示例中,我们可以在子组件中包含数据取取器(和数据)。这在Vue 2中是不可能的,因为:
在Vue 2中,最简单的方法实际上是通过支持将数据加载到父组件并将结果传递给子组件。如果你有很多子组件,这个模式可能会变得很混乱。
在Vue 3中,加载数据和检查条件的责任完全由子组件承担。父级不需要访问实际情况。
就像<template>一样,<Suspense>不创建DOM元素。
在上面的Vue 3示例中,<RenderItems />是可悬浮的。
发布于 2021-01-18 13:34:29
一个可挂起的组件将能够使用Vue 3中的新项。一个悬念项可以加载并且可能需要更长的时间来加载,比如API调用。通常,您将在悬念项内的项目中使用异步/等待。
这里有很多好信息:https://v3.vuejs.org/guide/component-dynamic-async.html#async-components
在等待悬念项中的项目时,您可以使用悬念项来表示其他内容(比如骨架加载程序)。
https://stackoverflow.com/questions/65774063
复制相似问题