<component:is="组件名变量"></component>
只要在data里定义一个变量,给变量赋值就能动态的切换组件。这个其实在某些场景还是非常好用的安利一下,例如:tab切换组件
<template> <div class="main"> <div class="left-menu"> <ul> <li v-for="(item, index) in menuList" :key="index" @click="changeList(index)" :class="{ active: selectIndex == index }" > <i :class="item.icon"></i> {{ item.name }} </li> </ul> </div> <div class="right-cont"> <component :is="comList"></component> </div> </div> </template> <script> export default { components: { home: () => import("@/components/table/index"), read: () => import("@/components/form/index"), total: () => import("@/components/total/index") }, data() { return { menuList: [ { icon: "el-icon-position", name: "首页" }, { icon: "el-icon-reading", name: "阅读" }, { icon: "el-icon-time", name: "时间" } ], comLists: ["home", "read", "total"], selectIndex: 0 }; }, computed: { comList() { return this.comLists[this.selectIndex]; } }, methods: { changeList(index) { this.selectIndex = index; } }, created() { } }; </script> <style> .main { display: flex; height: 100%; } .left-menu { width: 100px; border: 1px solid #ff7300; } .left-menu ul { padding: 0; margin: 0; } .left-menu ul li { list-style: none; display: flex; justify-content: center; height: 80px; } .right-cont { width: calc(100% - 100px); } .active { color: #f00; } </style>