Vue动态组件使用原生HTML元素的可行性及prop兼容问题解决方案
问题解答
基础疑问确认
Vue的:is属性完全支持直接传入原生HTML标签名作为值,你对这部分的用法本身是符合规范的,当前写法的问题确实是全量绑定的属性存在兼容性问题:原生<a>标签不支持foo这类自定义props,冗余属性挂载虽然不会直接报错,但属于无效的冗余逻辑。
可行解决方案
方案1:v-if分支拆分(优先推荐)
直接拆分两个渲染分支,各自绑定对应需要的属性,逻辑最清晰,无冗余属性问题:
<template> <ModalComponent v-if="active" :foo="Test" :class="$style.container" ref="link" > <Avatar /> </ModalComponent> <a v-else :href="href" :class="$style.container" ref="link" > <Avatar /> </a> </template> <script> import ModalComponent from '@/component/ModalComponent'; import Avatar from '@/component/Avatar'; export default { components: { ModalComponent, Avatar }, props: ['active', 'href'], data() { return { Test: '你的自定义值' } } } </script>
适合绝大多数场景,维护成本最低。
方案2:动态属性绑定(保留动态组件写法)
如果插槽内容复杂不想重复编写,可以通过计算属性动态返回对应目标需要的属性集合,用v-bind统一绑定:
<template> <component :is="active ? ModalComponent : 'a'" v-bind="componentProps" :class="$style.container" ref="link" > <Avatar /> </component> </template> <script> import ModalComponent from '@/component/ModalComponent'; import Avatar from '@/component/Avatar'; export default { components: { ModalComponent, Avatar }, props: ['active', 'href'], data() { return { Test: '你的自定义值' } }, computed: { componentProps() { return this.active ? { foo: this.Test } : { href: this.href } } } } </script>
注意:如果ModalComponent是局部注册的组件,:is里直接传导入的组件变量即可,不需要加引号;如果是全局注册的组件可以传字符串名称。
内容的提问来源于stack exchange,提问作者user15909643
相关产品推荐
相关产品推荐

