当应用多 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 } }}