Nuxt.js点击元素添加移除激活类 仅当前点击项生效如何实现
实现方案
你原来的代码问题在于直接操作document.body,导致激活类被绑定到body节点上。在Vue中不需要手动操作DOM,用响应式状态管理激活状态即可,以下是可直接运行的实现:
完整代码(推荐用循环写法,方便后续扩展)
<template> <div class="dashContent"> <div v-for="(item, index) in itemList" :key="index" class="dashContent_item" :class="{ 'dashContent_item--active': activeIndex === index }" @click="activeIndex = index" > <p class="dashContent_text">{{ item.text }}</p> </div> </div> </template> <script> export default { data() { return { // 存储当前激活项的索引,默认0对应第一个项激活 activeIndex: 0, // 选项数据,可根据需求自由扩展 itemList: [ { text: '123' }, { text: '456' }, { text: '789' } ] } } } </script> <style lang="scss"> .dashContent { &_item { display: flex; align-items: center; } &_text { color: #8e8f93; font-size: 14px; } } .dashContent_item--active { .dashContent_text{ color:#fff; font-size: 14px; } } </style>
不想用循环的硬写版本
<template> <div class="dashContent"> <div class="dashContent_item" :class="{ 'dashContent_item--active': activeIndex === 0 }" @click="activeIndex = 0" > <p class="dashContent_text">123</p> </div> <div class="dashContent_item" :class="{ 'dashContent_item--active': activeIndex === 1 }" @click="activeIndex = 1" > <p class="dashContent_text">456</p> </div> <div class="dashContent_item" :class="{ 'dashContent_item--active': activeIndex === 2 }" @click="activeIndex = 2" > <p class="dashContent_text">789</p> </div> </div> </template> <script> export default { data() { return { activeIndex: 0 } } } </script> <!-- 样式部分和你原有代码完全一致,不需要修改 -->
逻辑说明
- 用响应式变量
activeIndex记录当前选中项的序号,默认值为0对应首项默认激活 - 点击对应项时直接更新
activeIndex为当前项的序号 - 动态类绑定会自动匹配当前序号,只给对应项加激活类,其他项的激活类会自动移除,不需要手动操作DOM
- 该写法在Nuxt环境下可直接运行,无需额外调整
内容的提问来源于stack exchange,提问作者vvvychikov
相关产品推荐
相关产品推荐

