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>

这样一来,以后再有新的业务类型增加,也仅仅需要引入和注册业务组件即可,加载的事情自动就完成了!

posted @ 2020-07-22 11:11  荣光无限  阅读(5815)  评论(0编辑  收藏  举报