动态组件动态导入组件

969 阅读1分钟

正常组件使用

 // 1. 导入组件
 import A from './A.vue'
 // 2. 配置组件
 components: {
     A
 }
 // 3. 使用组件
    <A />

动态组件

  1. 上面所展示的是最基本的操作,组件名、组件个数、组件路径确定,可按照常规步骤引入、使用。
  2. 当不确定组件名、组件个数、组件路径 时, 为了避免所有组件渲染, 则使用动态组件,渲染对应组件。
     <component :is="activeComponent"></component>
     
     // 1. 导入多个组件
     import A from './A'
     import B from './B'
     import C from './C'
     // ...
     
     // 2. 配对组件
     data(){
         return {
             activeComponent: 'A'
         }
     }

动态组件动态导入

  1. 当不确定组件太多,10、20、30...n个的时候,如果将所有组件都导入首先导入组件步骤重复且繁琐,为了只导入当前不确定active组件, 如何引入组件、如何使用组件?
    <component :is="activeComponent"></component>
    
    computed:{
        activeComponent(){
            if(this.active){
                 let path = `./compontents/${this.active}` // 读取active组件路径信息
                let component = () => import(`${path}`);          // 动态组件
                return component
              } else {
                  return null
              }
        }
  }