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

1,830 阅读1分钟
  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>