1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > vue3异步组件怎么获取ref 获取组件实例?曲线救国的方式。

vue3异步组件怎么获取ref 获取组件实例?曲线救国的方式。

时间:2024-01-13 08:59:15

相关推荐

vue3异步组件怎么获取ref 获取组件实例?曲线救国的方式。

翻看文档实在没找到异步组件加载成功后的回调,获取ref写个setTimeout延迟个一两秒可以,万一网速慢就GG,所以还是得明确的知道这个组件什么时候下载引入成功的。

目前的思路是把defineAsyncComponent包装一层,获取import后的promise就行。

import {defineAsyncComponent,defineComponent } from "vue";/** * 创建一个异步组件* 方便之后能知道该组件是否下载完成*/function createAsyncComponent(fn){//注意使用的时候 promise需要返回原本的reslet component_ = undefined;function componentFn(){if(component_) return component_;const component = fn();component_ = component;return component;}const component = defineAsyncComponent(componentFn);return {component:component,componentFn:componentFn,};}const asyncComponent = createAsyncComponent(()=>{return import("@/views/research/asyncComponent");});export default defineComponent({name: 'Component',components: {asyncComponent:ponent,},setup() {ponentFn().finally(()=>{console.log("组件已经引入!(不代表已经渲染)");});},});

如果在使用组件前提前调用且是 .then() 调用的话,需要原封不动的把组件模块数据返回出去,像这样:

componentFn().then((res)=>{console.log("组件已经引入!(不代表已经渲染)");return res;});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。