Stories

Detail Return Return

vue動態組件綁定動態屬性和方法的小tips - Stories Detail

當使用多 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-bindv-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
      }
    }
}
user avatar honwhy Avatar 6fafa Avatar u_16307147 Avatar wszgrcy Avatar aresn Avatar taotao123 Avatar songxianling1992 Avatar nidexiaoxiongruantangna Avatar yazi_6005853a842a6 Avatar 13592899917 Avatar patelo Avatar fisher_feng Avatar
Favorites 37 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.