vue3中动态组件的踩坑记录分享
1.动态组件绑定问题
上周用vue3的动态组件替换了v-fo循环的页面,在实际中遇到了一个头疼的问题。组件单独写是可以出来,但使用动态组件却提示组件未注册
组件未注册
<template>
<div>
<div class="top text-center">
<el-radio-group v-model="currentMode" size="medium">
<el-radio-button v-for="(item, i) in menuList" :key="item.value" :label="item.value">
{{ item.label }}
</el-radio-button>
</el-radio-group>
</div>
<component :is="currentMode"></component>
</div>
</template>
<script setup>
import Plan1 from './plan1.vue';
import Plan2 from './plan2.vue';
import Plan3 from './plan3.vue';
import { ref } from 'vue';
const menuList = [
{ label: 'Plan1', value: 'Plan1' },
{ label: 'Plan2', value: 'Plan2' },
{ label: 'Plan3', value: 'Plan3' },
];
const currentMode = ref(menuList[0].value);
</script>
<style lang="scss" scoped></style>
报错信息
vue 3 Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
我以为是setup 写法 name丢失的问题
在百度上看到最多的还是将“name”属性默认导出,尝试了也无济于事。
就去仔细,查了下vue文档

官方建议使用三元表达式来实现动态组件:is="someCondition ? Foo : Bar"
解决方案
更具这个思路,那就很好处理了,只要将currentMode的值设置为elevator、airCond不就好了,搞个键值对映射就可以搞定了
function getComponent() {
const component = {
Plan1: Plan1,
Plan2: Plan2,
Plan3: Plan3,
};
return component[loadCountFlag.value];
}
最后将 getComponent()赋值给动态组件,刷新页面查看控制台,页面无报错

如果你的动态组件过多,可以使用defineAsyncComponent来实现组件懒加载,类似vue2中箭头函数的写法Plan1: () =>import('./Plan1.vue'),
<template>
<component :is="getComponent()" />
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// Assuming loadCountFlag is a reactive reference
const loadCountFlag = ref(1);
// Lazy-load components
const Plan1 = defineAsyncComponent(() => import('./components/Plan1.vue'));
const Plan2 = defineAsyncComponent(() => import('./components/Plan2.vue'));
const Plan3 = defineAsyncComponent(() => import('./components/Plan3.vue'));
function getComponent() {
const componentMap = {
1: Plan1,
2: Plan2,
3: Plan3,
};
return componentMap[loadCountFlag.value];
}
</script>
2.动态组件的方法导出问题
动态组件解决了,之前每个组件还有一个数据保存的方法,需要在父页面自动调用,并暴漏出去

于是这就很简单吗,直接使用vue2中this.$refs.xxx.xxx不就好了
正当我高高兴兴提交完代码准备下班时,测试的同事把我叫住了说自动保存没触发,数据丢失了
问了了GPT:

打开vue工具,组件切换检查了下,发现确实在变

于是我尝试着打印currentComponent.value?.saveData方法,控制台出现了。但是上层打印的确实undefind
组件切换的时候,autoSave应该动态切换,autoSave应该时响应式的,那么问题就解决了
解决办法:
使用computed包裹一层

问题解决,下班!
到此这篇关于vue3中动态组件的踩坑记录分享的文章就介绍到这了,更多相关vue3动态组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
vite2打包的时候vendor-xxx.js文件过大的解决方法
vite2是一个非常好用的工具,只是随着代码的增多,打包的时候 vendor-xxxxxx.js 文件也越来越大,本文主要介绍了vite2打包的时候vendor-xxx.js文件过大的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-03-03
详解Vue的钩子函数(路由导航守卫、keep-alive、生命周期钩子)
这篇文章主要介绍了详解Vue的钩子函数(路由导航守卫、keep-alive、生命周期钩子),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-07-07
Vue开发工具之vuejs-devtools安装教程及常见问题解决(最详细)
这篇文章主要介绍了Vue开发工具vuejs-devtools超级详细安装教程以及常见问题解决本篇文章是最详细的vue开发工具vuejs-devtools安装教程,需要的朋友可以参考下2022-11-11


最新评论