Vue的hover/click事件如何動態(tài)改變顏色和背景色
hover/click事件動態(tài)改變顏色和背景色
hover和click事件共存,動態(tài)改變按鈕背景色和文字顏色,不需要用到增刪class類,增刪class類是樣式寫死,體驗不好!
1.父組件內(nèi)容
<!-- :changeColor為傳入的顏色數(shù)據(jù) -->
<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.子組件內(nèi)容(配合路由跳轉(zhuǎn))
<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() {
//點擊實現(xiàn)路由跳轉(zhuǎn)
this.$router.replace(this.path);
},
itemHover() {
this.isHover = true;
},
removeHover() {
this.isHover = false;
},
},
};
</script>
vue頁面背景顏色修改
由于vue的單頁面應用導致我們的項目只有一個index.html文件,然而我們?nèi)粝敫淖冺撁娴谋尘吧谰票仨殑討B(tài)改變body的背景色才是最直觀最有效的解決方案。
廢話不多說直接上代碼,親測百分之百有效:
<template>
<div>
</div>
</template>
<script>
export default {
data() {
return {};
},
mounted(){},
methods: {},
//實例創(chuàng)建之前鉤子函數(shù)--給body添加行內(nèi)樣式
beforeCreate () {
this.$nextTick(()=>{
document.body.setAttribute('style', 'background:#EAECF1')
})
},
//實例銷毀之前鉤子--移除body 標簽的屬性style
beforeDestroy () {
document.body.removeAttribute('style')
}
};
</script>
<style lang="scss" scoped></style>下面說下為什么要在beforeCreate鉤子內(nèi)部用this.$nextTick鉤子包裹,this.$nextTick的作用是dom完全加載完成,所以我們改變body背景顏色是在操作dom
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue項目中input框focus時不調(diào)出鍵盤問題的解決
這篇文章主要介紹了Vue項目中input框focus時不調(diào)出鍵盤問題的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
使用vue + less 實現(xiàn)簡單換膚功能的示例
下面小編就為大家分享一篇使用vue + less 實現(xiàn)簡單換膚功能的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
web前端Vue報錯:Uncaught?(in?promise)?TypeError:Cannot?read?
這篇文章主要給大家介紹了關于web前端Vue報錯:Uncaught?(in?promise)?TypeError:Cannot?read?properties?of?nu的解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01
面試官常問的題之說一下Vue中setup的props和context
setup是一個組件選項,在組件被創(chuàng)建之前,props被解析之后執(zhí)行,這篇文章主要介紹了Vue中setup的props和context的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2026-04-04

