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') 為組件按需加載。當組件較多時這能顯著提高性能。