Vue的hover/click事件动态改变颜色和背景色

本文介绍了一种不使用增删class类的方法,通过hover和click事件动态改变按钮的背景色和文字颜色。利用Vue.js特性,实现按钮在鼠标悬停和点击状态下的颜色变化,同时支持路由跳转。

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

hover和click事件共存,动态改变按钮背景色和文字颜色,不需要用到增删class类,增删class类是样式写死,体验不好!

1.父组件内容
	  <!-- :changeColor为传入的颜色数据 -->
      <head-bar-item path="/home" :changeColor="{color: '#dc5d48', bgColor: '#373833'}">
        <template v-slot:item-text>首页</template>
      </head-bar-item>
      <head-bar-item path="/category">
        <template v-slot:item-text>分类</template>
      </head-bar-item>
2.子组件内容(配合路由跳转)
<template>
  <span
    class="tab-bar-item"
    :style="changeStyle"
    @click="itemClick"
    @mouseover="itemHover"
    @mouseout="removeHover"
  >
    <slot name="item-text"></slot>
  </span>
</template>

<script>
export default {
  name: "HeadBarItem",
  props: {
    path: String,
    changeColor: {
      type: Object,
      default() {
        return { color: "#dc5d48", bgColor: "#373833" };
      },
    },
  },
  data() {
    return {
      isHover: false,
    };
  },
  computed: {
    isActive() {
      return this.$route.path.includes(this.path);
    },
    //计算属性改变颜色核心
    //过程:如果按钮被点击了,则为用户传入的颜色,否则在判断鼠标是否移入改变了isHover,移入则变色,否则为默认值
    changeStyle() {
      return {
        color: this.isActive
          ? this.changeColor.color
          : this.isHover
          ? this.changeColor.color
          : "#f8f8f2",
        backgroundColor: this.isActive
          ? this.changeColor.bgColor
          : this.isHover
          ? this.changeColor.bgColor
          : "#545453",
      };
    },
  },
  methods: {
    itemClick() {
      //点击实现路由跳转
      this.$router.replace(this.path);
    },
    itemHover() {
      this.isHover = true;
    },
    removeHover() {
      this.isHover = false;
    },
  },
};
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值