单选
<div class="tabs" @click="goTurn">
<div
class="tab"
v-for="(tab, index) in tabs"
:key="index"
:class="{ active: activeTab === tab.id }"
:data-id="tab.id"
>
<div class="tab-bg">
<p>{{ tab.name }}</p>
</div>
</div>
</div>
import { debounce } from "@/assets/js/debounce.js";
//当前路由名称对应 tabId
const activeTab = ref(router.currentRoute.value.meta?.activeID || 0);
// 路由名称
const tabs = ref([
{
id: 1,
name: "政治",
},
{
id: 2,
name: "经济",
},
{
id: 3,
name: "文化",
},
{
id: 4,
name: "社会",
},
{
id: 5,
name: "生态",
},
]);
//事件委托跳转路由
const goTurn1 = debounce(() => {
router.replace("/");
activeTab.value = 0;
}, 100);
const goTurn = debounce((event) => {
event.preventDefault();
if (event.target instanceof HTMLElement) {
const element = event.target;
if (element.closest(".tab") instanceof HTMLElement) {
const tab = element.closest(".tab");
const tabId = tab?.dataset.id;
if (tabId) {
activeTab.value = Number(tabId);
switch (tabId) {
case "0":
router.replace("/home");
break;
case "1":
router.replace("/home/Politics");
break;
case "2":
router.replace("/home/Economics");
break;
case "3":
router.replace("/home/Culture");
break;
case "4":
router.replace("/home/Social");
break;
case "5":
router.replace("/home/Ecology");
break;
case "6":
router.replace("/home/");
break;
}
}
}
}
}, 100);
多选
<div class="tabs" @click="goTurn">
<!-- activeTab === tab.id -->
<div
class="tab"
v-for="(tab, index) in tabs"
:key="index"
:class="{ active: activeTab.filter((el: any) => el === Number(tab.id)).length > 0 }"
:data-id="tab.id"
>
<div class="tab-bg">
<p>{{ tab.name }}</p>
</div>
</div>
</div>
import { debounce } from "lodash-es";
const activeTab: any = ref([]); // 1
// tab名称
const tabs = ref([
{
id: 1,
name: "专业护理"
},
{
id: 2,
name: "医疗服务"
},
{
id: 3,
name: "生活照料"
},
{
id: 4,
name: "康复训练"
}
]);
//事件委托跳转路由
const goTurn = debounce(event => {
event.preventDefault();
if (event.target instanceof HTMLElement) {
const element = event.target;
if (element.closest(".tab") instanceof HTMLElement) {
const tab = element.closest(".tab");
const tabId = tab?.dataset.id;
if (tabId) {
if (activeTab.value.filter((el: any) => el === Number(tabId)).length === 0) {
activeTab.value.push(Number(tabId));
} else {
activeTab.value = activeTab.value.filter((el: any) => el != tabId);
}
// activeTab.value = Number(tabId);
// activeTab.value = Number(tabId);
}
console.log(activeTab.value);
}
}
}, 100);
效果图 (多选、取消选中)
