Vue 如何優雅的根據條件動態顯示組件


常規情況下,在 里動態加載不同組件的方式為:

<template>
    <!--  符合條件A,加載組件A -->
    <BusinessComponentA  v-if="condition==''A" />
    <!--  符合條件B,加載組件B -->
    <BusinessComponentB  v-if="condition=='B'" />
    <!--  符合條件C,加載組件C -->
    <BusinessComponentC  v-if="condition=='C'" />
</template>

這種方式的問題,就是如果有很多種業務場景,那么在template里就需要寫很多的分支.

✅ 解決辦法: 根據業務條件動態去匹配應該加載的業務組件,完整代碼如下

  <template>
  <div class="business-container">
    <!-- 🚀 component 標簽已經代表當前這個是一個組件 🚀 -->
    <!-- 🚀 只需要加載computed里計算出來的組件即可 🚀 -->
    <component v-bind:is="currentBizComponent"></component>
  </div>
</template>

<script>
    import BusinessComponentA from './components/BusinessComponentA'
    import BusinessComponentB from './components/BusinessComponentB'
    import BusinessComponentC from './components/BusinessComponentC'

    export default {
      components: { BusinessComponentA, BusinessComponentB, BusinessComponentC },
      data: function () {
        return {
         }
      },
      computed: {
        // 業務類型
        condition:function(){
          // 當前頁面數據 bizDoc
          return this.$store.state.bizDoc.type // should return A || B || C
        },
      // 🚀 當前應該加載的組件
        currentBizComponent: function () {
          return 'BusinessComponent' +  this.condition
        }
      }
    }
</script>
<style lang="scss">
.business-container {
  font-size: 20px;
  padding: 50px;
  height: 1000px;
  background-color: #ffff;
  text-align: center;
}
</style>

這樣一來,以后再有新的業務類型增加,也僅僅需要引入和注冊業務組件即可,加載的事情自動就完成了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM