vue 开发系列(九) VUE 动态组件的应用

业务场景

我们在开发表单的过程中会遇到这样的问题,我们选择一个控件进行配置,控件有很多中类型,比如文本框,下来框等,这些配置都不同,因此需要不同的配置组件来实现。

较常规的方法是使用v-if 来实现,这样界面看上去比较复杂,而且需要进行修改主页面。

解决方案

可以使用动态组件来实现,为了体现动态组件的特性,我们简化实现方式,编写两个简单的组件来测试一下这个功能。

文本组件配置:

<template>
  <div>
    我是单行文本框{{config.type}}
  </div>
</template>

<script>
  export default {
    name:"rx-textbox-config",
    props:{
      config:Object
    }
  }
</script>

<style>
</style>

这个组件我统一配置一个config 的对象属性,配置一个type 属性。

多行文本框配置:

<template>
  <div>
    我是多行文本框{{config.name}}
  </div>
</template>

<script>
  export default {
    name:"rx-textarea-config",
    props:{
      config:Object
    }
  }
</script>

<style>
</style>

这里我配置一个 name的属性。

在调用界面做写如下代码,导入组件

export default {
  name: 'App',
  components: {
    rxTextboxConfig,
    rxTextareaConfig,
  }

使用动态组件:

 <component :is="currentConfig" :config="config"></component>

使用代码切换组件

 this.currentConfig=ctlType +"-config";
      if(ctlType=="rx-textbox"){
          this.config.type="VARCHAR";
      }
      if(ctlType=="rx-textarea"){
          this.config.name="我是富文本框";
      }

这里写if 只是为了体现这个特性,实际实现不用这种方式。

原文地址:https://www.cnblogs.com/yg_zhang/p/11956066.html