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); }, //計算屬性改變顏色核心 //過程:如果按鈕被點擊了,則為用戶傳入的顏色,否則在判斷鼠標(biāo)是否移入改變了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的單頁面應(yīng)用導(dǎo)致我們的項目只有一個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 標(biāo)簽的屬性style beforeDestroy () { document.body.removeAttribute('style') } }; </script> <style lang="scss" scoped></style>
下面說下為什么要在beforeCreate鉤子內(nèi)部用this.$nextTick鉤子包裹,this.$nextTick的作用是dom完全加載完成,所以我們改變body背景顏色是在操作dom
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Ant Design Vue Pro動態(tài)路由加載,服務(wù)器重啟首頁白屏問題
這篇文章主要介紹了Ant Design Vue Pro動態(tài)路由加載,服務(wù)器重啟首頁白屏問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vue之input輸入框防抖debounce函數(shù)的使用方式
這篇文章主要介紹了vue之input輸入框防抖debounce函數(shù)的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11vue+vuex+json-seiver實現(xiàn)數(shù)據(jù)展示+分頁功能
這篇文章主要介紹了vue+vuex+json-seiver實現(xiàn)數(shù)據(jù)展示+分頁功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04