vue中有个内置组件component,利用它可以实现动态组件,在某些业务场景下可以替换路由
假设有以下三个组件:
com1、com2、com3
有一个外层路/coms中代码如下
1 <template> 2 <div class="container"> 3 <component :is="activeItem"/> 4 <button @click="changeActiveItem">切换</button> 5 </div> 6 </template> 7 <script> 8 export default { 9 name:"coms", 10 data(){ 11 return { 12 activeItem:'com1' 13 } 14 }, 15 components:{ 16 com1:()=>import('@/components/com-1.vue'), 17 com2:()=>import('@/components/com-2.vue'), 18 com3:()=>import('@/components/com-3.vue'), 19 }, 20 methods:{ 21 changeActiveItem(){ 22 this.activeItem = this.activeItem === 'com1' ? 23 'com2' : this.activeItem === 'com2' ? 24 'com3' : 'com1' 25 } 26 } 27 } 28 </script>
那么这就实现了一个简单的动态路由了。
但是我现在有另外一种场景,那就是需要在某个页面展示不确定数量的组件,具体展示什么组件由权限判断后后端返回一个数组。
即我要同时显示三个组件中的0-3个组件,很容易想到用v-if判断是否存在于数组中来动态显示,稍显麻烦且不提,如果我要根据后台数据改变顺序呢?
这种时候循环往往是有效的,用数组长度个component组件就可以了嘛。
1 <template> 2 <div class="container"> 3 <component :is="item" v-for="item in allComponents" :key="item" /> 4 </div> 5 </template> 6 <script> 7 export default { 8 name:"coms", 9 data(){ 10 return { 11 allComponents:['com1','com2'] 12 } 13 }, 14 components:{ 15 com1:()=>import('@/components/com-1.vue'), 16 com2:()=>import('@/components/com-2.vue'), 17 com3:()=>import('@/components/com-3.vue'), 18 } 19 } 20 </script>
注:()=>import('@/components/com-1.vue') 为组件按需加载。当组件较多时这能显著提高性能。