vue3中动态组件的踩坑记录分享
作者:本末倒置183
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动态组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
