您好,欢迎访问一九零五行业门户网

快速了解Vue3中的Fragment、Suspense、Portal特性

本篇文章带大家了解一下vue3中的3个新特性fragment(碎片化节点)、suspense(异步组件)、portal(传送门),希望对大家有所帮助。
vue3中新增了一些功能来解决vue2中那些戳中开发人员痛楚的诟病。同时,也对vue2中性能进行了优化。本文带你一起探讨vue3中新增的fragment、teleport和suspense的使用方法。
fragment(碎片化节点)不知道各位有没有在vue2中遇到过下图中的报错信息:
这是vue2抛出的错误提示。意思是说组件只能有一个根元素。当我们新建一个vue页面时,通常会有多个不同的元素节点。我们会在最外层包裹一个div来使其让它成为这个页面的根节点。但这并不友好。有时候我们并不需要这个div元素。
vue3中解决了这个问题。vue3中新增了一个类似dom的标签元素0a17e00161c48f1f864ee8c9188914dc5a79ca7a0b5af47915e68afdaed2e68c。如果在vue页面中有多个元素节点。那么编译时vue会在这些元素节点上添加一个0a17e00161c48f1f864ee8c9188914dc5a79ca7a0b5af47915e68afdaed2e68c标签。并且该标签不会出现在dom树中。
suspense(异步组件)vue3中提供一个bb06e69d307cb52103d07d8f9dd385e508ee156419279e45977839a62de7dfe8组件用于控制异步组件。
//创建一个异步组件<script>const { createapp,defineasynccomponent } = vueconst app = createapp({})const asynccomp = defineasynccomponent( () => new promise((resolve, reject) => { settimeout(() => resolve({ template: '<div>i am async!</div>' }),3000) }))app.component('async-component', asynccomp)app.mount('#app')</script>
用suspense包裹异步组件 async-component
<suspense> <template #default> <async-component /> </template> <template #fallback> loading ... </template> </suspense>
上面的异步组件使用了定时器,3秒后显示该组件 我们可以通过defineasynccomponent提供一系列的参数来定义异步组件
import { defineasynccomponent } from 'vue'const asynccomp = defineasynccomponent({ // 工厂函数 loader: () => import('./foo.vue'), // 加载异步组件时要使用的组件 loadingcomponent: loadingcomponent, // 加载失败时要使用的组件 errorcomponent: errorcomponent, // 在显示 loadingcomponent 之前的延迟 | 默认值:200(单位 ms) delay: 200, // 如果提供了 timeout ,并且加载组件的时间超过了设定值,将显示错误组件 // 默认值:infinity(即永不超时,单位 ms) timeout: 3000, // 定义组件是否可挂起 | 默认值:true suspensible: false, /** * * @param {*} error 错误信息对象 * @param {*} retry 一个函数,用于指示当 promise 加载器 reject 时,加载器是否应该重试 * @param {*} fail 一个函数,指示加载程序结束退出 * @param {*} attempts 允许的最大重试次数 */ onerror(error, retry, fail, attempts) { if (error.message.match(/fetch/) && attempts <= 3) { // 请求发生错误时重试,最多可尝试 3 次 retry() } else { // 注意,retry/fail 就像 promise 的 resolve/reject 一样: // 必须调用其中一个才能继续错误处理。 fail() } }})
当配置项中的suspensible为true时,被suspense包裹的异步组件将会被控制
portal(传送门)在vue2中我们可能会使用例如element-ui,iview等组件库,有时候我们会发现这些ui组件库中的某些组件渲染层级并不包含在vue dom中。如 modal toast等组件的层级就在vue dom 之外。这种在vue之外的层级方便我们进行全局处理和管理。vue3中提供一对<teleport ></teleport>用于移动dom的层级
<div id="app"> <h1>hello async component</h1> <com-a /></div><div class="i-can-fly"></div>// 组件aconst { createapp } = vueconst componenta = { template: `<com-b><com-b/><div class="i-can-fly">我能瞬间移动</div>` }const componentb ={template: `<div class="i-can-fly">我能飞</div>`}const app = createapp({})app.component('com-b',componentb)app.component('com-a',componenta)app.mount('#app')
此时我们打开控制台查看元素
渲染的结果如下。然后我们修改代码添加teleport标签
<div id="app"> <----...---> <teleport to=".i-can-fly"> <com-a /> </teleport></div><div class="i-can-fly"></div>
此时我们发现组件b已经不在app中了。而是出现在了以类选择器为i-can-fly的div中。
值得注意的是 teleport标签上的to参数表示要将包裹的内容所移动到的位置。
【相关推荐:vue.js教程】
以上就是快速了解vue3中的fragment、suspense、portal特性的详细内容。
其它类似信息

推荐信息