1. vue中代码准备
<template>
<div>
<div class="nav">
<p v-for="(item, index) in navName" :key="index">{{ item }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
navName: ["导航1", "导航2", "导航3", "导航4", "导航5"],
};
},
};
</script>
<style scoped>
.nav {
width: 500px;
display: flex;
justify-content: space-between;
align-items: center;
}
.green {
color: #85f;
}
</style>>
展示到页面结果如图 : 
2. 实现目标:点击其中一个导航菜单,使其变成绿色
实现步骤:
2.1. 声明一个变量,来控制类是否添加
data() {
return {
isH: 0, //新声明的变量,用来控制那个导航菜单可以添加类名
navName: ["导航1", "导航2", "导航3", "导航4", "导航5"],
};
},
2.2 给 p 标签添加点击事件,同时获取点击时的下标(index)
@click="changeCheck(index)"
methods: {
changeCheck(index) {
this.isH = index;
},
},
2.3 给 p 标签添加类名(需要判断点击的是具体的那个对象)
:class="{ green: index === isH }"
3 目标实现
3.1 完整代码如下:
<template>
<div>
<div class="nav">
<p
:class="{ green: index === isH }"
@click="changeCheck(index)"
v-for="(item, index) in navName"
:key="index"
>
{{ item }}
</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isH: 0,
navName: ["导航1", "导航2", "导航3", "导航4", "导航5"],
};
},
methods: {
changeCheck(index) {
this.isH = index;
},
},
};
</script>
<style scoped>
.nav {
width: 500px;
display: flex;
justify-content: space-between;
align-items: center;
}
p {
cursor: pointer;
}
.green {
color: #85f;
}
</style>>
效果展示如图:  有意见,请指出,谢谢
|