当你想做一个动态的tabs,根据导航条来加入标签页面时,你可以用到vue的内置组件***ponent
***ponent
***ponent是VUE提供的一个内置特殊元素,用于渲染动态组件或元素的“元组件”
要渲染的实际组件由 is prop 决定。
当 is 是字符串,它既可以是 HTML 标签名也可以是组件的注册名。
或者,is 也可以直接绑定到组件的定义。
<***ponent :is="item.type === 1 ? ***ponentA : ***ponentB"
:nodeObj="item.nodeObj"
@renderTree="renderTree"
:ref="(el) => set***ponentRef(item.key, el)" ></***ponent>
***ponent同时也接受转递过去的数据和方法,用法跟普通的组件是一样的
特别需要注意的ref绑定的对象,ref要保证唯一性,我们要通过ref来访问不同组件暴露出来的方法
const ***ponentRefs = reactive({});
const set***ponentRef = (key, el) => {
if (el) {
***ponentRefs[key] = el;
} else {
delete ***ponentRefs[key];
}
};
tabs加***ponent
完整代码块
vue部分
<Tabs class="!h-full" v-model:activeKey="activeKey" type="editable-card" hideAdd size="small" @edit="editTabs" @change="onTabsChange">
<TabPane v-for="item in content***trTabRecs" :key="item.key" >
<template #tab>
{{ item.title }}
</template>
<***ponent :is="item.type === 1 ? ***ponentA : ***ponentB"
:nodeObj="item.nodeObj"
@renderTree="renderTree"
:ref="(el) => set***ponentRef(item.key, el)" >
</***ponent>
</TabPane>
</Tabs>
ts部分
const activeKey = ref('');
const content***trTabRecs = reactive<any[]>([]);
content***trTabRecs.push({key: value.id, title: value.title,nodeObj:{
//...
},type:1})
const ***ponentRefs = reactive({});
const set***ponentRef = (key, el) => {
if (el) {
***ponentRefs[key] = el;
} else {
delete ***ponentRefs[key];
}
};
//访问ref
const current***ponentRef = ***ponentRefs[node.id];
if(current***ponentRef){
//操作逻辑
}