動態

詳情 返回 返回

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

當使用多 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 頭像 6fafa 頭像 u_16307147 頭像 wszgrcy 頭像 aresn 頭像 taotao123 頭像 songxianling1992 頭像 nidexiaoxiongruantangna 頭像 yazi_6005853a842a6 頭像 13592899917 頭像 patelo 頭像 fisher_feng 頭像
點贊 37 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.