当使用多 tab 内容页时,动态组件是一件非常好用的利器。但是循环动态组件会有个问题,那就是不同组件绑定不同的属性值和方法,全部写在组件内固然是一种方法,就是不方便管理和查看,所以以下是单独声明的技巧小 tips。
切换的tabs常量
const TABS = [
{
label: 'tab1',
compo: 'RankingList',
props: [
'currentLiveCourse',
'teacherList',
'teacherIdObj',
'teacherNameObj',
'showCashbackRuleDialog',
'teacherLoading'
]
},
{
label: 'tab2',
compo: 'ExpertVideo',
listeners: {
playVideo: 'playVideo'
}
}
]
component页面代码
对于.sync
等修饰符的方法需要单独赋值。
// tabs 是切换的tab
<component
v-for="(item, index) in tabs"
:key="index"
:is="item.compo"
v-bind="item.props && tabCompoProps(item.props)"
v-on="item.listeners && tabCompoListeners(item.listeners)"
@update:showCashbackRuleDialog="showCashbackRuleDialog = $event"
/>
computed计算属性获取值
v-bind
和v-on
用来绑定多个属性和方法,这个地方得用计算属性来获取,否则对于异步数据获取不到。
computed: {
// 动态组件绑定的属性值
tabCompoProps () {
return (arr) => arr.reduce((acc, cur) => {
acc[cur] = this[cur]
return acc
}, {})
},
// 动态组件绑定的事件
tabCompoListeners () {
return (listeners) => {
for (const listener in listeners) {
listeners[listener] = this[listener]
}
return listeners
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。