效果图:
思路:通过 :class来和三元运算符来动态绑定
给v-for绑定一个单击事件,这个单击事件里传输下标索引,用于获取用户点击的是哪一个
定义一个n来存储传过来的下标值
最后在:class中判断n是否==与下标索引
代码:
<template> <div :class="[className ==i ? 'active' : '']" v-for="(t, i) in titles" :key="t.id" @click="classFunction(i)"> {{ t.title }} </div> </template> <script lang="ts" setup> import { reactive, ref } from 'vue'; let className=ref(0); let titles = reactive([ { id: 1, title: "默认" }, { id: 2, title: "销量" }, { id: 3, title: "价格" }, { id: 4, title: "好评" }, { id: 5, title: "出版时间" } ]) function classFunction(i:any){ className.value=i } </script> <style scoped> </style>
标签:title,绑定,class,reactive,数组,ref,id From: https://www.cnblogs.com/zsbb/p/16872921.html