Vue的hover/click事件如何动态改变颜色和背景色
作者:流浪者°
这篇文章主要介绍了Vue的hover/click事件如何动态改变颜色和背景色问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
hover/click事件动态改变颜色和背景色
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>
vue页面背景颜色修改
由于vue的单页面应用导致我们的项目只有一个index.html文件,然而我们若想改变页面的背景色美酒必须动态改变body的背景色才是最直观最有效的解决方案。
废话不多说直接上代码,亲测百分之百有效:
<template>
<div>
</div>
</template>
<script>
export default {
data() {
return {};
},
mounted(){},
methods: {},
//实例创建之前钩子函数--给body添加行内样式
beforeCreate () {
this.$nextTick(()=>{
document.body.setAttribute('style', 'background:#EAECF1')
})
},
//实例销毁之前钩子--移除body 标签的属性style
beforeDestroy () {
document.body.removeAttribute('style')
}
};
</script>
<style lang="scss" scoped></style>下面说下为什么要在beforeCreate钩子内部用this.$nextTick钩子包裹,this.$nextTick的作用是dom完全加载完成,所以我们改变body背景颜色是在操作dom
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
