16-动态组件

Huxzhi大约 1 分钟vue3

什么是动态组件 就是:让多个组件使用同一个挂载点,并动态切换,这就是动态组件。

同样的功能实现还有 v-if 标签路由选择

在挂载点使用 component 标签,然后使用 v-bind :is=”组件”

用法如下

引入组件

import A from './A.vue'
import B from './B.vue'
<component :is="A"></component>

通过 is 切换 A B 组件

使用场景 tab切换 居多

注意事项

1.在 Vue2 的时候 is 是通过组件名称切换的 在 Vue3 setup 是通过组件实例切换的

2.如果你把组件实例放到 Reactive Vue 会给你一个警告

runtime-core.esm-bundler.js:38 [Vue warn]: Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`.
Component that was made reactive:

这是因为 reactive 会进行 proxy 代理 而我们组件代理之后毫无用处 节省性能开销 推荐我们使用 shallowRef 或者 markRaw 跳过 proxy 代理

修改如下

const comId = shallowRef(AVue)

//...

const tab = reactive<Com[]>([{
    name: "A组件",
    comName: markRaw(A)
}, {
    name: "B组件",
    comName: markRaw(B)
}])

兼容 Vue2 的写法

用字符串的形式,源码里面作了区分,if 判断