我们在项目中会有这种情况,根据点击侧边栏的菜单,来动态实现右侧tabs的增减,那么这种效果怎么实现呢
1.模板部分
<el-menu :collapse="isCollapse" active-text-color="#ffd04b" background-color="#242424" class="el-menu-vertical-demo" :default-active="onRoutes" text-color="#fff" :router="true" :unique-opened="true" :collapse-transition="true" ><MenuTree:menuList="userStore.menuRouters"></MenuTree> </el-menu>
<!-- 内容展示区 --> <div class="layout_main"> <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab" @tab-click="clickBtn"> <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name"> <Main></Main> </el-tab-pane> </el-tabs> <!-- <Main></Main> --> </div>
2.方法部分
import { ref, computed, inject, watch, onMounted } from 'vue' import { useRoute, useRouter } from 'vue-router'; const router = useRouter(); const route = useRoute() onMounted(() => { router.push({ name: 'Home' }); }) // 面包屑导航动态删减 const editableTabs = ref([ { title: '首页', name: 'Home', path: '/home' } ]) const editableTabsValue = ref('Home') const removeTab = (targetName) => { const tabs = editableTabs.value; let activeName = editableTabsValue.value; if (tabs.length === 2) { // 检查是否只剩一个标签页 activeName = 'Home'; // 设置为首页 router.push({ name: 'Home' }); // 跳转到首页 } else if (activeName === targetName) { tabs.forEach((tab, index) => { if (tab.name === targetName) { const nextTab = tabs[index + 1] || tabs[index - 1]; if (nextTab) { activeName = nextTab.name; } } }); } editableTabsValue.value = activeName; editableTabs.value = tabs.filter(tab => tab.name !== targetName); router.push({ name: activeName }); } const clickBtn = (tab) => { router.push({ name: tab.props.name }) } watch(route, (newVal) => { const exists = editableTabs.value.some(tab => tab.name === newVal.name) if (!exists && newVal.name !== 'home') { editableTabs.value.push({ title: newVal.meta.title, name: newVal.name, path: newVal.path }) } editableTabsValue.value = newVal.name })
效果如下:
项目地址:https://github.com/jiaokaihang/vite_project.githttps://github.com/jiaokaihang/vite_project.git
npm install
npm run dev
喜欢的小伙伴github点个start 如有问题请联系qq 2096864475
标签:el,const,name,tabs,Menu,value,newVal,tab From: https://blog.csdn.net/qq_65949679/article/details/140843090