Vue里实现点击获取当前元素并新增class类

需求

点击icon后,icon变为灰色

解决思路

    点击icon后,获取当前dom,增加visited类 css里visited类加样式

代码

1、点击事件传参数 $event

<a-tooltip>
	 <template #title>显示详情</template>
	 <a><a-icon type="idcard" @click="showAnalyze(record, $event)"/></a>
 </a-tooltip>

2、接收参数,event.currentTarget为该点击事件绑定的元素对象,className为该元素的class类值

showAnalyze(record, event) {
          
   
	this.analyzeVisible = true
	this.analyzeModel = record
	event.currentTarget.className = visited anticon anticon-idcard
}

3、css增加类样式

.visited {
          
   
  opacity: 0.8!important;
  color: gray!important;
}

注意点

    currentTarget为该点击事件绑定的元素对象,target为当前点击到的元素对象,如果你的点击元素存在嵌套的情况,请用前者,因为使用target每次点击到元素不确定 第三方的UI库部分组件会动态修改元素的类名,比如tooltip,当你发现你修改的className不生效时,可定位下是否该原因导致的 点击到svg标签修改className时,会报错

参考

经验分享 程序员 微信小程序 职场和发展