凸显选中的小栗子
最下方有完整代码cv走可以进行调试。
html部分解释
-
Tab 按钮: 使用
v-for
遍历tabs
数组中的每个对象,生成相应数量的 tab 按钮。通过:class
动态绑定类名,当currentIndex
等于当前循环的索引时,添加active
类,以突显当前选中的 tab。 -
显示当前选中的 Tab 内容: 使用
v-show
根据currentIndex
的值来条件性地显示当前选中的 tab 内容。
js部分解释
-
数据部分(data): 在
data
函数中定义了组件的初始状态,包括tabs
数组和currentIndex
。tabs
数组中包含了每个 tab 的名称和内容,而currentIndex
表示当前选中的 tab 的索引。 -
方法部分(methods): 提供了
changeTab
方法,当 tab 被点击时触发,用于更新currentIndex
,从而切换到相应的 tab。
cs部分解释
通过添加样式,突显了选中的 tab。.active
类被定义为加粗文字、蓝色文本、并改变鼠标指针形状,以提高交互性。
完整代码
<template>
<div>
<!-- Tab 按钮 -->
<div
v-for="(tab, index) in tabs"
:key="index"
@click="changeTab(index)"
:class="{ active: currentIndex === index }"
>
{
{ tab.name }}
</div>
<!-- 显示当前选中的 Tab 内容 -->
<div v-show="currentIndex === selectedTab">
{
{ tabs[currentIndex].content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: 'Tab 1', content: 'Content for Tab 1' },
{ name: 'Tab 2', content: 'Content for Tab 2' },
{ name: 'Tab 3', content: 'Content for Tab 3' },
],
currentIndex: 0, // 默认选中第一个 Tab
};
},
methods: {
changeTab(index) {
this.currentIndex = index;
},
},
};
</script>
<style>
/* 添加样式以突显选中的 Tab */
.active {
font-weight: bold;
color: blue;
cursor: pointer;
}
</style>