Vue的hover/click事件动态改变颜色和背景色
Vue的hover/click事件动态改变颜色和背景色父组件内容父组件内容<head-bar-item path="/home" :changeColor="{color: '#dc5d48', bgColor: '#373833'}"><template v-slot:item-text>首页</template></head-bar-item>.
·
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>
更多推荐
已为社区贡献3条内容
所有评论(0)