vue选项组通过点击实现Class切换

本文介绍如何在Vue.js项目中实现一个动态高亮的导航栏,通过使用v-for指令生成选项组,并利用v-bind绑定class实现点击切换高亮效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 首先使用v-for指令动态生成选项组

html

<ul class="content clear">
        <li v-for="(item, index) in items" :key="index">{{item.title}}</li>
      </ul>

js

data() {
    return {
      items: [
        { title: '首页' },
        { title: '消息' },
        { title: '发现' },
        { title: '关于' },
        { title: '联系我们' },
      ],
    };
  },
  1. 在data中定义一个变量来存储当前点击的元素索引(index)

js

return {
      activeIndex: 0, // 0为默认选中第一项,-1为不选
  1. 在li标签中添加点击事件和在methods中写addClass方法

html

<li @click="addClass(index)"  // 这里需要传index

js

methods: {
    addClass(index) {
      this.activeIndex = index; // 把当前所点击元素的index,赋值给activeIndex
    },
  },
  1. 使用v-bind绑定class

html

<li :class="activeIndex === index ? 'active':''"
  1. 定义动态类的样式
.active{
    color: #fff;
    background-color: #42b983;
  }

在这里插入图片描述
全部代码:

<template>
    <div class="info">
      <ul class="content clear">
        <li :class="activeIndex === index ? 'active':''"
            @click="addClass(index)"
            v-for="(item, index) in items"
            :key="index">
            {{item.title}}
        </li>
      </ul>
    </div>
</template>

<script>
export default {
  name: 'Info',
  data() {
    return {
      activeIndex: 0, // 0为默认选中第一项,-1为不选
      items: [
        { title: '首页' },
        { title: '消息' },
        { title: '发现' },
        { title: '关于' },
        { title: '联系我们' },
      ],
    };
  },
  methods: {
    addClass(index) {
      this.activeIndex = index; // 把当前所点击元素的index,赋值给activeIndex
    },
  },
};
</script>

<style lang="scss">
  .info{
    width: 400px;
    margin: 0 auto;
    .content{
      li{
        list-style: none;
        float: left;
        padding: 10px;
        cursor: pointer;
      }
    }
  }
  .active{
    color: #fff;
    background-color: #42b983;
  }
  .clear{
    content: '';
    display: table;
    clear: both;
  }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值